如何使用OkHttp 2.0实现Android Volley?

14

1
那个Gist上已经有一条评论,指向支持HttpStack的OkHttp 2.0版本 - CommonsWare
1
是的,但是ceram1发布的类具有自定义缓存处理。我正在寻找最简单的方法。而且,我不知道那个实现是否最优/标准/正确。 - JohnRock
3个回答

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
我使用了这个解决方案,并添加了以下 gradle 依赖项: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

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
我认为这比@fjmontiel的回答更易读,但除此之外完全相同,不是吗? - Sotti
是的!根据需求,有许多可用的Gist,例如用于SSL HTTPS的https://gist.github.com/tbruyelle/0729aef4df2c11b21fdf。 - LOG_TAG

2

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接