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)

Is it possible to disable following redirects in OkHttp 2.0?

In Android, I'd like to use the new OkHttp 2.0 to request some URLs, but I'd like more control over redirects. I've already found the option to enable or disable following HTTPS → HTTP or HTTP → HTTPS redirects, but I'd like to not follow any redirects, so I can update my GUI as soon as possible, and choose whether to follow them from application logic. I don't see an option to do this. Is it possible, and if so, how can I achieve this?

Source: (StackOverflow)

How to implement cookie handling on Android using OkHttp?

Using OkHttp by Square, how can I:

  1. Retrieve a cookie returned from the server
  2. Store the cookie for upcoming requests
  3. Use the stored cookie in subsequent requests
  4. Update the cookie returned by the subsequent request

Ideally the cookie would be stored, resent and updated automatically with every request.

Source: (StackOverflow)

How to set connection timeout with OkHttp

I am developing app using OkHttp library and my trouble is I cannot find how to set connection timeout and socket timeout.

   OkHttpClient client = new OkHttpClient();

   Request request = new Request.Builder().url(url).build();

   Response response = client.newCall(request).execute();


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)

Retrofit + Okhttp cancel operation not working

I am using retrofit in my application like this

 final OkHttpClient okHttpClient = new OkHttpClient();
 okHttpClient.interceptors().add(new YourInterceptor());

            final OkClient okClient = new OkClient(okHttpClient);
            Builder restAdapterBuilder = new RestAdapter.Builder();
                    .setEndpoint("some url");
            final RestAdapter restAdapter =;

public class YourInterceptor implements Interceptor {

    public Response intercept(Chain chain) throws IOException {
        // TODO Auto-generated method stub
        Request request = chain.request();

        if (request != null) {
            Request.Builder signedRequestBuilder = request.newBuilder();
            request =;
        return chain.proceed(request);

after sending request i am calling


but request is not cancelling i am getting the response from retrofit dont know why it is not cancelling my request

I need volley like cancelation retrofit

Source: (StackOverflow)

How to retry HTTP requests with OkHttp/Retrofit?

I am using Retrofit/OkHttp (1.6) in my Android project.

I don't find any request retry mechanism built-in to either of them. On searching more, I read OkHttp seems to have silent-retries. I don't see that happening on any of my connections (HTTP or HTTPS). How to configure retries with okclient ?

For now, I am catching exceptions and retrying maintaining a counter variable.

Source: (StackOverflow)

Tracking progress of multipart file upload using OKHTTP

I am trying to implement a a progress bar to indicate the progress of a multipart file upload.

I have read from a comment on this answer - that I have to wrap the sink passed to the RequestBody and provide a callback that tracks the bytes moved.

I have created a custom RequestBody and wrapped the sink with a CustomSink class, however through debugging I can see that the bytes are being written by RealBufferedSink ln 44 and the custom sink write method is only run once, not allowing me to track the bytes moved.

    private class CustomRequestBody extends RequestBody {

    MediaType contentType;
    byte[] content;

    private CustomRequestBody(final MediaType contentType, final byte[] content) {
        this.contentType = contentType;
        this.content = content;

    public MediaType contentType() {
        return contentType;

    public long contentLength() {
        return content.length;

    public void writeTo(BufferedSink sink) throws IOException {
        CustomSink customSink = new CustomSink(sink);


private class CustomSink implements BufferedSink {

    private static final String TAG = "CUSTOM_SINK";

    BufferedSink bufferedSink;

    private CustomSink(BufferedSink bufferedSink) {
        this.bufferedSink = bufferedSink;

    public void write(Buffer source, long byteCount) throws IOException {
        Log.d(TAG, "source size: " + source.size() + " bytecount" + byteCount);
        bufferedSink.write(source, byteCount);

    public void flush() throws IOException {

    public Timeout timeout() {
        return bufferedSink.timeout();

    public void close() throws IOException {

    public Buffer buffer() {
        return bufferedSink.buffer();

    public BufferedSink write(ByteString byteString) throws IOException {
        return bufferedSink.write(byteString);

    public BufferedSink write(byte[] source) throws IOException {
        return bufferedSink.write(source);

    public BufferedSink write(byte[] source, int offset, int byteCount) throws IOException {
        return bufferedSink.write(source, offset, byteCount);

    public long writeAll(Source source) throws IOException {
        return bufferedSink.writeAll(source);

    public BufferedSink writeUtf8(String string) throws IOException {
        return bufferedSink.writeUtf8(string);

    public BufferedSink writeString(String string, Charset charset) throws IOException {
        return bufferedSink.writeString(string, charset);

    public BufferedSink writeByte(int b) throws IOException {
        return bufferedSink.writeByte(b);

    public BufferedSink writeShort(int s) throws IOException {
        return bufferedSink.writeShort(s);

    public BufferedSink writeShortLe(int s) throws IOException {
        return bufferedSink.writeShortLe(s);

    public BufferedSink writeInt(int i) throws IOException {
        return bufferedSink.writeInt(i);

    public BufferedSink writeIntLe(int i) throws IOException {
        return bufferedSink.writeIntLe(i);

    public BufferedSink writeLong(long v) throws IOException {
        return bufferedSink.writeLong(v);

    public BufferedSink writeLongLe(long v) throws IOException {
        return bufferedSink.writeLongLe(v);

    public BufferedSink emitCompleteSegments() throws IOException {
        return bufferedSink.emitCompleteSegments();

    public OutputStream outputStream() {
        return bufferedSink.outputStream();

Does anybody have an example of how I would go about doing this?

Source: (StackOverflow)

How can I pin a certificate with Square OKHTTP?

I think I need to create a new SSL Socket Factory? Also, I don't want to use the global SSL Context ( for obvious reasons.



As of okhttp 2.1.0 you can pin certificates very easily.

See the source code here to get started

Source: (StackOverflow)