我正在使用 okhttp3 向服务器发出请求,而不是使用改造。我的想法是拨打电话并将响应保存在缓存中 15 分钟。如果在这 15 分钟内再次发出请求,则恢复缓存响应,15 分钟后,再次从服务器请求它。这是我的代码:public class Handler_JSON_get { public Handler_JSON_get() { } public String makeServiceCall(String url, JSONObject data) { final MediaType JSON = MediaType.parse("application/json; charset=utf-8"); Cache cache = new Cache(new File(Environment.getExternalStorageDirectory().getPath() + "/Android/data/MY_PACKAGE/", "cache"), 10 * 1024 * 1024); OkHttpClient okHttpClient; Log.i("2134","Usando caché"); okHttpClient = new OkHttpClient.Builder() .addNetworkInterceptor(provideCacheInterceptor()) .readTimeout(45, TimeUnit.SECONDS) .protocols(Arrays.asList(Protocol.HTTP_1_1)) .addInterceptor(provideCacheInterceptor()) .cache(cache) .build(); Request request = new Request.Builder() .url(url) .get() .build(); try { Response response = okHttpClient.newCall(request).execute(); Log.i(TAG,"Response:"+response.code()); return response.body().string(); } catch (Exception e) { e.printStackTrace(); return null; } } Interceptor provideCacheInterceptor() { return new Interceptor() { @Override public Response intercept(Interceptor.Chain chain) throws IOException { Response response = chain.proceed(chain.request()); CacheControl cacheControl = new CacheControl.Builder() .maxAge(15, TimeUnit.MINUTES) .build(); return response.newBuilder() .header("cache", cacheControl.toString()) .build(); } }; }}问题是他总是打电话给服务器,我有很多疑问。okhttp3 负责查看存储中是否有缓存的响应?该调用保存了一个日志文件,这是正确的文件吗?我错过了什么或者我做错了什么?
1 回答
慕的地8271018
TA贡献1796条经验 获得超4个赞
我花了一些时间才发现:正确的标头名称是Cache-Control
,而不是cache
:
return response.newBuilder() .header("Cache-Control", cacheControl.toString()) .build();
另外似乎添加拦截器 withaddNetworkInterceptor
就足够了,没有必要也添加它 withaddInterceptor
添加回答
举报
0/150
提交
取消