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);

CustomOkClientImpl.java

package com.wolmerica.example;
 
import android.content.Context;
import android.util.Log;
import java.io.File;
import java.io.IOException;
import java.net.CookieHandler;
import java.net.CookieManager;
import java.net.CookiePolicy;
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) {
e.printStackTrace();
Log.i(“OkClient”, “IOException: ” + e.getMessage());
}
 
            okHttpClient.setResponseCache(cache);
}
 
        if (withCookie) {
Log.i(“OkClient”, “withCookie logic”);
CookieManager cm = new CookieManager();
cm.setCookiePolicy(CookiePolicy.ACCEPT_ALL);
okHttpClient.setCookieHandler(cm);
}
 
        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 *