使用OKHttp处理Volley的底层HTTP请求

1) 导入Volley(目前没有官方的jar包,需要自己下载源码编译);

1
git clone https://android.googlesource.com/platform/frameworks/volley

2) 导入OkHttpokhttp-urlconnection

3) 创建OkHttpStack

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
/**
* An {@link com.android.volley.toolbox.HttpStack HttpStack} implementation which
* uses OkHttp as its transport.
*/
public class OkHttpStack extends HurlStack {
private final OkHttpClient client;
public OkHttpStack() {
this(new OkHttpClient());
}
public OkHttpStack(OkHttpClient client) {
if (client == null) {
throw new NullPointerException("Client must not be null.");
}
this.client = client;
}
@Override protected HttpURLConnection createConnection(URL url) throws IOException {
return client.open(url);
}
}

4) 创建Volley队列

1
Volley.newRequestQueue(context, new OkHttpStack());

参考链接:OkHttp作者Jake Wharton的Gist