我认为使用 OkHttp作为其传输的VolleyHttpStack
实现是最好的解决方案
RequestQueue queue = Volley.newRequestQueue(this);
Network network = new BasicNetwork(new OkHttpStack());
RequestQueue queue = new RequestQueue(new DiskBasedCache(new File(getCacheDir(), "volley")), network);
queue.start();
OkHttpStack 类:
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);
}
}
更新:
如果您使用的是新版本的 okhttp 堆栈,请使用
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);
}
@Override
protected HttpURLConnection createConnection(URL url) throws IOException {
return mFactory.open(url);
}
}