如何使用OkHttp 2.0实现Android Volley?

时间:2014-06-23 20:49:05

标签: android android-volley okhttp

OkHttp2.0不再支持此OkHttpStack: https://gist.github.com/JakeWharton/5616899

将OkHttp 2.0.0与Volley集成的当前模式是什么?

3 个答案:

答案 0 :(得分:30)

您必须使用实现java.net.HttpURLConnection API的okhttp-urlconnection模块,因此:

  • 下载或设置okhttp-urlconnection

  • 的依赖关系
  • 重写OkHttpStack以使用OkUrlFactory类:

    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);
       }
    }

答案 1 :(得分:5)

您也可以使用

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);
    }
}

答案 2 :(得分:2)

您现在也可以在不依赖HttpURLConnection的情况下执行此操作:

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

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