Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement Android Volley with OkHttp 2.0?

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?

like image 965
JohnRock Avatar asked Jun 23 '14 20:06

JohnRock


People also ask

Does volley use OkHttp?

Volley by default uses as transport layer the Apache Http stack on Froyo and HttpURLConnection stack on Gingerbread and above. Nowadays there's no many reasons to use those anymore and the good news is Volley allow us to easily set up OkHttp as its transport layer.

Does Android use OkHttp?

squareup. okhttp , artifactId, okhttp and the version 2.5. 0 (current as of this writing). As of Android 5.0, OkHttp is part of the Android platform and is used for all HTTP calls.

What is the difference between retrofit and OkHttp?

OkHttp is a pure HTTP/SPDY client responsible for any low-level network operations, caching, requests and responses manipulation. In contrast, Retrofit is a high-level REST abstraction build on top of OkHttp. Retrofit is strongly coupled with OkHttp and makes intensive use of it.

Why retrofit is faster than volley?

Volley may be relying on a library bundled with your OS, hence updating the network client isn't an option. Retrofit makes it much easier to configure HTTP intercepts (if you want to do something before or after an HTTP call).


1 Answers

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);
       }
    }
like image 121
franmontiel Avatar answered Sep 20 '22 14:09

franmontiel