An HTTP+SPDY client for Android and Java applications. OkHttp an http & spdy client for android and java applications

Is Retrofit+Okhttp using httpCaching as a default in Android?

I use retrofit and okhttp in one of our applications.

I can't really find a good explanation for the default behaviour of Retrofit.

If Okhttp is on the class path it will be automatically used. But as far as I can see it the default HttpResponseCache is null.

Do I need to explicitly enable caching with Retrofit and Okhttp?

Source: (StackOverflow)

How to configure the Http Cache when using Volley with OkHttp?

I want to try Volley combining with OkHttp but Volley cache system and OkHttp both rely on the HTTP cache as defined in the HTTP specification. So how can be disabled the cache of OkHttp for keeping one copy of HTTP cache?

EDIT: what I have done

public class VolleyUtil {
    private volatile static RequestQueue sRequestQueue;

    /** get the single instance of RequestQueue **/
    public static RequestQueue getQueue(Context context) {
        if (sRequestQueue == null) {
            synchronized (VolleyUtil.class) {
                if (sRequestQueue == null) {
                    OkHttpClient client = new OkHttpClient();
                    client.networkInterceptors().add(new StethoInterceptor());
                    sRequestQueue = Volley.newRequestQueue(context.getApplicationContext(), new OkHttpStack(client));
                    VolleyLog.DEBUG = true;
        return sRequestQueue;

Which OkHttpClient is referenced from

Source: (StackOverflow)

How to add parameters to api (http post) using okhttp library in Android

In my Android application, I am using okHttp library. How can I send parameters to the server(api) using the okhttp library? currently I am using the following code to access the server now need to use the okhttp library.

this is the my code:

httpPost = new HttpPost("");
nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("email".trim(), emailID));
nameValuePairs.add(new BasicNameValuePair("password".trim(), passWord));
httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
String response = new DefaultHttpClient().execute(httpPost, new BasicResponseHandler());

Source: (StackOverflow)

Android Picasso library, How to add authentication headers?

I have tried setting a custom OkHttpClient with a custom Authenticator, however as the doc says: "Responds to authentication challenges from the remote web or proxy server." I have to make 2 requests for each image, and that is not ideal.

Is there a request interceptor like Retrofit does? Or am I missing something in the OkHttpClient?

I'm using the latest versions:

compile 'com.squareup.picasso:picasso:2.3.2'
compile 'com.squareup.okhttp:okhttp:2.0.+'
compile 'com.squareup.okhttp:okhttp-urlconnection:2.0.+'
compile 'com.squareup.okio:okio:1.0.0'


Source: (StackOverflow)

OkHTTP and Picasso don't run together

I use Picasso library in my project to load images ande cache them. It works good without any problem. However, when I try to use OkHttp library to perform data communication with my server (JSON communication), Picasso throws exceptions.

I use the following jars : okhttp-2.0.0-RC2, okio-1.0.0, picasso-2.2.0. When I run my project after I add these jars, It crashes with the following :

06-12 11:13:15.824: E/dalvikvm(12105): Could not find class 'com.squareup.okhttp.HttpResponseCache', referenced from method com.squareup.picasso.OkHttpDownloader.<init>

I added okhttp just to use the following method :

public static String executeHttpGet(String urlStr) {
    Response response = null;
    String result = "";
    OkHttpClient client = new OkHttpClient();

    try {
        Request request = new Request.Builder().url(urlStr).build();

        response = client.newCall(request).execute();
        result = response.body().string();
    } catch (Exception ex) {

    return result;

The above code works without any problem. However the codes which use Picasso library and used to work perfectly, start to throw the following excecption :

06-12 11:19:49.307: E/AndroidRuntime(13036): FATAL EXCEPTION: main
06-12 11:19:49.307: E/AndroidRuntime(13036): java.lang.NoClassDefFoundError: com.squareup.okhttp.HttpResponseCache
06-12 11:19:49.307: E/AndroidRuntime(13036):    at com.squareup.picasso.OkHttpDownloader.<init>(
06-12 11:19:49.307: E/AndroidRuntime(13036):    at com.squareup.picasso.OkHttpDownloader.<init>(
06-12 11:19:49.307: E/AndroidRuntime(13036):    at com.squareup.picasso.OkHttpDownloader.<init>(
06-12 11:19:49.307: E/AndroidRuntime(13036):    at com.squareup.picasso.Utils$OkHttpLoaderCreator.create(
06-12 11:19:49.307: E/AndroidRuntime(13036):    at com.squareup.picasso.Utils.createDefaultDownloader(
06-12 11:19:49.307: E/AndroidRuntime(13036):    at com.squareup.picasso.Picasso$
06-12 11:19:49.307: E/AndroidRuntime(13036):    at com.squareup.picasso.Picasso.with(

My Class Path :

enter image description here

If I remove okhttp-2.0.0-RC2, okio-1.0.0, Picasso lines work.

Why is that happening ? How can I use two libraries together ?

Source: (StackOverflow)

Retrofit connection failure returns RetrofitError.response as null

Using Retrofit 1.6.0, OkHTTP 2.0.0, and OkHTTP-UrlConnection 2.0.0.

I am doing a POST to a service using Retrofit to a URL that does not exist. The failure callback is called, as expected. However, the RetrofitError parameter does not have a response. I would really like to grab the HTTP status code that was returned by using


but since getResponse() returns null, I can't.

Why is getResponse() null and how can I get the status?


Also, the error I am receiving is UnknownHostException, as expected. Repeat: I am expecting this error. I want to know how to get the HTTP status code or why error.getResponse() returns null.

Edit: Here's some code:
    RestAdapter restAdapter = new RestAdapter.Builder()
    sService = restAdapter.create(ServiceInterface.class);
    void login(@Body JsonObject body, Callback<String> callback);
    public void failure(RetrofitError error) {
        if (error.getResponse() == null) {

            // error.getResponse() is null when I need to get the status code
            // from it.


Source: (StackOverflow)

NoSuchMethodError if i am using okhttp 2.0 and the latest retrofit?

Could not find method, referenced from method retrofit.client.OkClient.openConnection.

below is my gradle config

compile 'com.squareup.okhttp:okhttp:+'
compile 'com.squareup.okhttp:okhttp-urlconnection:+'
compile 'com.squareup.retrofit:retrofit:+'

Source: (StackOverflow)

OkHttp how to log request body

I'm using an interceptor, and I would like to log the body of a request I'm making but I can't see any way of doing this.

Is it possible ?

public class LoggingInterceptor implements Interceptor {
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();

        long t1 = System.nanoTime();
        Response response = chain.proceed(request);
        long t2 = System.nanoTime();

        double time = (t2 - t1) / 1e6d;

        if (request.method().equals("GET")) {
  "GET " + F_REQUEST_WITHOUT_BODY + F_RESPONSE_WITH_BODY, request.url(), time, request.headers(), response.code(), response.headers(), response.body().charStream()));
        } else if (request.method().equals("POST")) {
  "POST " + F_REQUEST_WITH_BODY + F_RESPONSE_WITH_BODY, request.url(), time, request.headers(), request.body(), response.code(), response.headers(), response.body().charStream()));
        } else if (request.method().equals("PUT")) {
  "PUT " + F_REQUEST_WITH_BODY + F_RESPONSE_WITH_BODY, request.url(), time, request.headers(), request.body().toString(), response.code(), response.headers(), response.body().charStream()));
        } else if (request.method().equals("DELETE")) {
  "DELETE " + F_REQUEST_WITHOUT_BODY + F_RESPONSE_WITHOUT_BODY, request.url(), time, request.headers(), response.code(), response.headers()));

        return response;

and the result :

POST  [some url] in 88,7ms
    ZoneName: touraine
    Source: Android
    body: retrofit.client.OkClient$1@1df53f05 <-request.body().toString() gives me this, but I would like the content string
    Response: 500
    Date: Tue, 24 Feb 2015 10:14:22 GMT
    body: [some content] 

Source: (StackOverflow)

Does android use okhttp internally?

This is a stack trace I get when running an android app I recently inherited. We're not using okhttp as an explicity dependency, and the in the trace makes me think the aosp is using okhttp now internally?

java.lang.Throwable: Explicit termination method 'close' not called
                        E      at
                        E      at
                        E      at
                        E      at
                        E      at
                        E      at
                        E      at
                        E      at
                        E      at
                        E      at
                        E      at
                        E      at
                        E      at

Source: (StackOverflow)

How to get response body to retrofit exception?

I am trying to connect to rest service via retrofit in android application. I am getting responses. But when there is some error response from the service, conversion exception occurs and now I want to do some actions based on the response body. But I am getting response body as NULL. But retrofit log has a error message. Why is this happening.

04-14 18:57:35.686: D/Reftofit log(24856): OkHttp-Received-Millis: 1397527055676
04-14 18:57:35.686: D/Reftofit log(24856): OkHttp-Response-Source: NETWORK 200
04-14 18:57:35.686: D/Reftofit log(24856): OkHttp-Sent-Millis: 1397527055492
04-14 18:57:35.686: D/Reftofit log(24856): Server: Apache/2.2.22 (Ubuntu)
04-14 18:57:35.686: D/Reftofit log(24856): X-Powered-By: PHP/5.3.10-1ubuntu3.10
04-14 18:57:35.701: D/Reftofit log(24856): {"result":"Invalid Token ID"}


  public void failure(RetrofitError arg0) {
                String response = null;

                TokenError r = (TokenError) arg0
                response = r.getErrorDetails();

                Log.e(TAG, response);
                if (response != null
                        && response.contains("Invalid Token ID"))


Here I am getting r as NULL. I don't know why? Do I need to set something with rest adapter so that the response will be passed to retrofit error object.

Source: (StackOverflow)

How to specify a default user agent for okhttp 2.x requests

I am using okhttp 2.0 in my Android app and didn't find a way to set some common User Agent for all outgoing requests.

I thought I could do something like

OkHttpClient client = new OkHttpClient();

...but there's no such method or similar. Of course I could provide some extension utility method which would wrap a RequestBuilder to attach .header("UserAgent") and then I would use it for building all my requests, but I thought maybe I missed some existing and simpler way?

Source: (StackOverflow)

Using OKHttp, what is the difference between synchronous request in AsyncTask and OKhttp Asynchronous request?

OKHttp supports both synchronous and asynchronous api. If I want to issue an async request, I can:

  1. Use a AsyncTask, and issue OKhttp synchronous api.
  2. Issue a OKhttp asynchronous api.

What is the difference between these 2 options? And which one is better?

Source: (StackOverflow)

Retrofit + RxJava fails to cache responses, suspected response headers

I'm trying to configure cache with Retrofit 1.9.0 and OkHtttp 2.5.0.

Here is how I provide OkHttpClient for my RestAdapter:

public OkHttpClient provideOkHttpClient() {
    OkHttpClient okHttpClient = new OkHttpClient();
    okHttpClient.setConnectTimeout(TIMEOUT_IN_SECONDS, TimeUnit.SECONDS);
    okHttpClient.setReadTimeout(TIMEOUT_IN_SECONDS, TimeUnit.SECONDS);
    okHttpClient.setWriteTimeout(TIMEOUT_IN_SECONDS, TimeUnit.SECONDS);

    File cacheDir = new File(context.getCacheDir(), "http");
    final Cache cache = new Cache(cacheDir, DISK_CACHE_SIZE_IN_BYTES);

    okHttpClient.interceptors().add(new Interceptor() {
        public Response intercept(Chain chain) throws IOException {

            Response response = chain.proceed(request);
            Response finalResponse = response.newBuilder()
                    .header("Cache-Control", String.format("public, max-stale=%d", 604800))

            Log.d("OkHttp", finalResponse.toString());
            Log.d("OkHttp Headers", finalResponse.headers().toString());
            return finalResponse;

    return okHttpClient;

I did not forget to setClient on RestAdapter.Builder. Also made sure, that I'm actually using instance of RestAdapter with this client set.

Even checked if the files are created under "http" folder. They are.

However after I turn of WIFI and reload my screen I end up in OnError callback of Observable endpoint with this message:

retrofit.RetrofitError: failed to connect to / (port 8888) after 10000ms: connect failed: ENETUNREACH (Network is unreachable)

DISCLAIMER: I should probably mention that the final Observable is combined from 5 others, with flatMap and zip on the way.

Source: (StackOverflow)

retrofit + okhttp : Retrieve GZIPInputStream

I have a problem when i activate gzip on WS using retrofit 1.4.1 and okhttp 1.3.0.

RequestInterceptor requestInterceptor = new RequestInterceptor() {
            public void intercept(RequestFacade request) {
                request.addHeader("content-type", "application/json");
                request.addHeader("accept-encoding", "gzip");  // Here is the problem
RestAdapter restAdapter = new RestAdapter.Builder()

If I comment the following line request.addHeader("accept-encoding", "gzip"); there is no problem but if gzip is activated, i get an error (my request falls in failure).

Here is my logcat with request.addHeader("accept-encoding", "gzip");

1326               Retrofit  D  : HTTP/1.1 200 OK
  1326               Retrofit  D  Cache-Control: public, max-age=600
  1326               Retrofit  D  Content-Encoding: gzip
  1326               Retrofit  D  Content-Length: 254
  1326               Retrofit  D  Content-Type: application/json
  1326               Retrofit  D  Date: Wed, 05 Feb 2014 20:22:26 GMT
  1326               Retrofit  D  OkHttp-Received-Millis: 1391631746193
  1326               Retrofit  D  OkHttp-Response-Source: NETWORK 200
  1326               Retrofit  D  OkHttp-Selected-Transport: http/1.1
  1326               Retrofit  D  OkHttp-Sent-Millis: 1391631745971
  1326               Retrofit  D  Server: Apache
  1326               Retrofit  D  Vary: Accept-Encoding
  1326               Retrofit  D  X-Powered-By: PHP/5.3.3-7+squeeze18
  1326               Retrofit  D  ������������}�?O�0��~����nHZOH0 �D�ù���?���~w.�:����=�{�
  1326               Retrofit  D  <--- END HTTP (254-byte body)
  1326             System.err  W  retrofit.RetrofitError: retrofit.converter.ConversionException: java.lang.Ille
                               galStateException: Expected BEGIN_OBJECT but was STRING at line 1 column 1
  1326             System.err  W  at retrofit.RestAdapter$RestHandler.invokeRequest(
  1326             System.err  W  at retrofit.RestAdapter$RestHandler.access$100(
  1326             System.err  W  at retrofit.RestAdapter$RestHandler$2.obtainResponse(
  1326             System.err  W  at
  1326             System.err  W  at java.util.concurrent.ThreadPoolExecutor.runWorker(
  1326             System.err  W  at java.util.concurrent.ThreadPoolExecutor$
  1326             System.err  W  at retrofit.Platform$Android$2$
  1326             System.err  W  at
  1326             System.err  W  Caused by: retrofit.converter.ConversionException: java.lang.IllegalStateExcep

How can I turn on gzip ?

Thx in advance

Source: (StackOverflow)

Retrofit 1.9 with OkHttp 2.2 and interceptors

I thought that these recent versions were supposed to be compatible. There is this tweet; and the changelog of Retrofit 1.9 mentions it too.

However when I try this:

        OkHttpClient httpClient = new OkHttpClient();
        httpClient.interceptors().add(new TokenExpiredInterceptor());

        mRestAdapter = new RestAdapter.Builder()
                .setLogLevel(BuildConfig.DEBUG ?
                        RestAdapter.LogLevel.FULL :
                .setRequestInterceptor(new AuthorizationInterceptor())

It still doesn't work. The setClient method complains about an incompatible Client object;

Error:(29, 21) error: no suitable method found for setClient(OkHttpClient)
method Builder.setClient(Client) is not applicable
(argument mismatch; OkHttpClient cannot be converted to Client)
method Builder.setClient(Provider) is not applicable
(argument mismatch; OkHttpClient cannot be converted to Provider)

What am I missing? I also see OkHttpClient does not implement the Client interface.

I am using this approach for now;

Did I misinterpret the changelog? Maye Retrofit 1.9 can uses OkHttpClient 2.2 when it's in the classpath but the interface isn't adapted yet?

Source: (StackOverflow)