相关疑难解决方法(0)

使用OKHttp进行改造可以在离线时使用缓存数据

我正在尝试使用Retrofit和OKHttp来缓存HTTP响应.我按照这个要点,结束了这段代码:

File httpCacheDirectory = new File(context.getCacheDir(), "responses");

HttpResponseCache httpResponseCache = null;
try {
     httpResponseCache = new HttpResponseCache(httpCacheDirectory, 10 * 1024 * 1024);
} catch (IOException e) {
     Log.e("Retrofit", "Could not create http cache", e);
}

OkHttpClient okHttpClient = new OkHttpClient();
okHttpClient.setResponseCache(httpResponseCache);

api = new RestAdapter.Builder()
          .setEndpoint(API_URL)
          .setLogLevel(RestAdapter.LogLevel.FULL)
          .setClient(new OkClient(okHttpClient))
          .build()
          .create(MyApi.class);
Run Code Online (Sandbox Code Playgroud)

这是带有Cache-Control标头的MyApi

public interface MyApi {
   @Headers("Cache-Control: public, max-age=640000, s-maxage=640000 , max-stale=2419200")
   @GET("/api/v1/person/1/")
   void requestPerson(
           Callback<Person> callback
   );
Run Code Online (Sandbox Code Playgroud)

首先,我在线请求并检查缓存文件.有正确的JSON响应和标题.但是当我尝试离线请求时,我总是得到RetrofitError UnknownHostException.我还有什么办法让Retrofit从缓存中读取响应吗?

编辑: 因为OKHttp 2.0.x HttpResponseCacheCache …

java caching offline-caching retrofit okhttp

142
推荐指数
5
解决办法
8万
查看次数

使用OkHttp进行缓存(不使用Retrofit)

在我的Application onCreate中,我正在创建一个10MB的缓存:

try
{
    File httpCacheDir = new File(getApplicationContext().getCacheDir(), Constants.AppName);
    long httpCacheSize = 10 * 1024 * 1024; // 10 MiB
    HttpResponseCache.install(httpCacheDir, httpCacheSize);
}
catch (IOException ex)
{
    Log.i(Constants.AppName, "HTTP response cache installation failed: " + ex);
}
Run Code Online (Sandbox Code Playgroud)

我对资源的调用:

OkHttpClient client = new OkHttpClient();
client.setResponseCache(HttpResponseCache.getInstalled());

HttpURLConnection connection = client.open(url);
connection.addRequestProperty("Cache-Control", "max-age=60");
InputStream inputStream = connection.getInputStream();
Run Code Online (Sandbox Code Playgroud)

我将在10秒内彼此初始化此调用两次,并且OkHttp-Response-Source标头始终为NETWORK 200.

for (Map.Entry<String, List<String>> k : connection.getHeaderFields().entrySet())
{
    for (String v : k.getValue())
    {
        Log.d(Constants.AppName, k.getKey() + ": " + v);
    }
}
Run Code Online (Sandbox Code Playgroud)

我在这里错过了什么?

android okhttp

1
推荐指数
1
解决办法
3051
查看次数

标签 统计

okhttp ×2

android ×1

caching ×1

java ×1

offline-caching ×1

retrofit ×1