Android OkHttpClient with cache and cookie support

Instantiate the CustomOkClientImpl and call configureOkClientImpl to get the OkClient as shown in the following example.  The okhttp-1.3.0-jar-with-dependencies.jar and retrofit-1.4.1.jar packages are required.

    Log.i(“ResetResults”, “call for new OkHttpClient()”);
    CustomOkClientImpl custHttpClient = new CustomOkClientImpl();
    OkClient okClient = custHttpClient.configureOkClientImpl(LoginActivity.this, true, true);

package com.wolmerica.example;
import android.content.Context;
import android.util.Log;
import com.squareup.okhttp.HttpResponseCache;
import com.squareup.okhttp.OkHttpClient;
import retrofit.client.OkClient;
public class CustomOkClientImpl {
    public OkClient configureOkClientImpl(Context connContext,Boolean withCache,                                                                               Boolean withCookie) {
        // Define an HttpClient to be used by RestAdapter.
Log.i(“OkClient”, “create a new OkHttpClient()”);
OkHttpClient okHttpClient = new OkHttpClient();
        if (withCache) {
Log.i(“OkClient”, “withCache logic”);
File cacheDir = connContext.getCacheDir();
HttpResponseCache cache = null;
            try {
cache = new HttpResponseCache(cacheDir, 1024);
} catch (IOException e) {
Log.i(“OkClient”, “IOException: ” + e.getMessage());
        if (withCookie) {
Log.i(“OkClient”, “withCookie logic”);
CookieManager cm = new CookieManager();
        return (new OkClient(okHttpClient));

About admin

Richard Wolschlager is the owner of Wolmerica Technologies LLC and holds a (93) Bachelors of Science degree in Computer Science with a minor in Mathematics from Saginaw Valley State University. Richard has worked in the Information Technology field for 20 years on a variety of platforms and lines of business.
This entry was posted in Android, Apache httpd, Java. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *