How to implement Android Volley with OkHttp 2.0?
Asked Answered
C

3

14

This OkHttpStack is no longer supported in OkHttp2.0: https://gist.github.com/JakeWharton/5616899

What is the current pattern to integrate OkHttp 2.0.0 with Volley?

Curiel answered 23/6, 2014 at 20:49 Comment(2)
There is a comment already on that gist pointing to an OkHttp 2.0 version of HttpStack support.Loseff
Yes, but the class that ceram1 posted has a customized cache handling. I was looking for the simplest way. And also, I have no idea if that implementation is optimal/standard/correctCuriel
S
30

You must use okhttp-urlconnection module that implements the java.net.HttpURLConnection API, so:

  • Download or set a dependency for okhttp-urlconnection

  • Rewrite your OkHttpStack to make use of the OkUrlFactory class:

    public class OkHttpStack extends HurlStack {
       private final OkUrlFactory okUrlFactory;
       public OkHttpStack() {
           this(new OkUrlFactory(new OkHttpClient())); 
       }
       public OkHttpStack(OkUrlFactory okUrlFactory) {
           if (okUrlFactory == null) {
               throw new NullPointerException("Client must not be null.");
           }
           this.okUrlFactory = okUrlFactory;
       }
       @Override
       protected HttpURLConnection createConnection(URL url) throws IOException {
           return okUrlFactory.open(url);
       }
    }
Service answered 2/7, 2014 at 12:39 Comment(1)
I used this solution and added the following gradle dependencies: compile 'com.squareup.okhttp:okhttp:2.0.0' compile 'com.squareup.okhttp:okhttp-urlconnection:2.0.0' compile 'com.squareup.okio:okio:1.0.1'Curiel
C
5

You can use this also

import com.android.volley.toolbox.HurlStack;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.OkUrlFactory;

/**
 * An {@link com.android.volley.toolbox.HttpStack HttpStack} implementation
 * which uses OkHttp as its transport.
 */
public class OkHttpStack extends HurlStack {
    private final OkUrlFactory mFactory;

    public OkHttpStack() {
        this(new OkHttpClient());
    }

    public OkHttpStack(OkHttpClient client) {
        if (client == null) {
            throw new NullPointerException("Client must not be null.");
        }
        mFactory = new OkUrlFactory(client);
    }
}
Clemens answered 25/7, 2014 at 8:56 Comment(2)
I think this is more readable than the @fjmontiel answer but besides that is exactly the same, isn't it?Dyedinthewool
yes!, there are many gist available depending upon the requirement like for ssl gist.github.com/tbruyelle/0729aef4df2c11b21fdfClemens
C
2

You can also do this now without the dependency on HttpURLConnection:

https://plus.google.com/+JakeWharton/posts/31jhDwaCvtg

https://gist.github.com/bryanstern/4e8f1cb5a8e14c202750

Calliecalligraphy answered 23/2, 2015 at 20:36 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.