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?

JohnRock
  • 6,795
  • 15
  • 52
  • 61
  • 1
    There is a comment already on that gist pointing to [an OkHttp 2.0 version of `HttpStack` support](https://gist.github.com/ceram1/8254f7a68d81172c1669). – CommonsWare Jun 23 '14 at 21:39
  • 1
    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/correct – JohnRock Jun 23 '14 at 21:52

3 Answers3

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);
       }
    }
franmontiel
  • 1,860
  • 1
  • 16
  • 20
  • 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'` – JohnRock Oct 14 '14 at 15:40
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);
    }
}
LOG_TAG
  • 19,894
  • 12
  • 72
  • 105
  • 2
    I think this is more readable than the @fjmontiel answer but besides that is exactly the same, isn't it? – Sotti Sep 08 '14 at 16:00
  • yes!, there are many gist available depending upon the requirement like for ssl https://gist.github.com/tbruyelle/0729aef4df2c11b21fdf – LOG_TAG Sep 09 '14 at 03:39
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

christoff
  • 587
  • 1
  • 6
  • 17