Xia*_*zou 20 android caching android-volley okhttp
我想尝试将Volley与OkHttp结合使用,但是Volley缓存系统和OkHttp都依赖于HTTP规范中定义的HTTP缓存.那么如何禁用OkHttp的缓存以保留一份HTTP缓存?
编辑:我做了什么
public class VolleyUtil {
// http://arnab.ch/blog/2013/08/asynchronous-http-requests-in-android-using-volley/
private volatile static RequestQueue sRequestQueue;
/** get the single instance of RequestQueue **/
public static RequestQueue getQueue(Context context) {
if (sRequestQueue == null) {
synchronized (VolleyUtil.class) {
if (sRequestQueue == null) {
OkHttpClient client = new OkHttpClient();
client.networkInterceptors().add(new StethoInterceptor());
client.setCache(null);
sRequestQueue = Volley.newRequestQueue(context.getApplicationContext(), new OkHttpStack(client));
VolleyLog.DEBUG = true;
}
}
}
return sRequestQueue;
}
}
Run Code Online (Sandbox Code Playgroud)
这OkHttpClient是从引用https://gist.github.com/bryanstern/4e8f1cb5a8e14c202750
Xia*_*zou 17
OkHttp是一种像HttpUrlConnection这样实现HTTP缓存的HTTP客户端,我们可以像下面那样禁用OkHttp的缓存:
OkHttpClient client = new OkHttpClient();
client.setCache(null);
Run Code Online (Sandbox Code Playgroud)
然后,我们可以保留Volley维护的一个HTTP缓存副本.
改进:
我想尝试回答索蒂的问题.
1我想知道使用Volley和OkHttp时什么是好的缓存设置.
在我的项目中,我在所有的restful API中使用了一个Volley requestQueue实例,而OkHttp则作为Volley的传输层工作,如下所示.
public class VolleyUtil {
// http://arnab.ch/blog/2013/08/asynchronous-http-requests-in-android-using-volley/
private volatile static RequestQueue sRequestQueue;
/** get the single instance of RequestQueue **/
public static RequestQueue getQueue(Context context) {
if (sRequestQueue == null) {
synchronized (VolleyUtil.class) {
if (sRequestQueue == null) {
OkHttpClient client = new OkHttpClient();
client.setCache(null);
sRequestQueue = Volley.newRequestQueue(context.getApplicationContext(), new OkHttpStack(client));
VolleyLog.DEBUG = true;
}
}
}
return sRequestQueue;
}}
Run Code Online (Sandbox Code Playgroud)
2我们应该依赖Volley还是OkHttp缓存?
是的,我正在使用Volley缓存来代替我的HTTP Cache而不是OkHttp Cache; 这对我很有效.
3开箱即用的默认行为是什么?
对于排球:
它会自动为您创建一个"凌空"默认缓存目录.
/** Default on-disk cache directory. */
private static final String DEFAULT_CACHE_DIR = "volley";
public static RequestQueue newRequestQueue(Context context, HttpStack stack, int maxDiskCacheBytes) {
File cacheDir = new File(context.getCacheDir(), DEFAULT_CACHE_DIR);
……
}
Run Code Online (Sandbox Code Playgroud)
对于OkHttp:
我找不到源代码中的默认缓存,我们可以设置响应缓存,就像这篇文章 http://blog.denevell.org/android-okhttp-retrofit-using-cache.html
4.建议的行为是什么以及如何实现?
正如这篇文章所说:
Volley负责请求,加载,缓存,线程,同步等.它已准备好处理JSON,图像,缓存,原始文本并允许一些自定义.
我更喜欢使用Volley HTTP Cache,因为它易于定制.
例如,我们可以对缓存进行更多控制,例如 Android Volley + JSONObjectRequest缓存.
| 归档时间: |
|
| 查看次数: |
1313 次 |
| 最近记录: |