3

我正在使用改造 1.8.0、okhttp 2.1.0 和 okhttp-urlconnection 2.1.0,我想缓存从服务器获得的响应并在没有互联网连接时使用它们,这是我的代码:

RequestInterceptor requestInterceptor = new RequestInterceptor() {

    @Override
    public void intercept(RequestFacade request) {

        request.addHeader("Accept", "application/json");
        if (Utils.isNetworkAvailable(HancoApplication.this)) {

            int maxAge = 60; // read from cache for 1 minute
            request.addHeader("Cache-Control", "public, max-age=" + maxAge);
        } else {

            int maxStale = 60 * 60 * 24 * 28; // tolerate 4-weeks stale
            request.addHeader("Cache-Control","public, only-if-cached, max-stale=" + maxStale);
        }
    }
};
OkHttpClient okHttpClient = new OkHttpClient();
File cacheDir = new File(getCacheDir(), "responseCache");
Cache cache = null;
try {

    cache = new Cache(cacheDir, 1024 * 1024 * 12);
    okHttpClient.setCache(cache);
} catch (IOException e) {

    e.printStackTrace();
}
RestAdapter restAdapter = new RestAdapter.Builder().setEndpoint(Const.API_URL).setClient(new OkClient(okHttpClient)).setRequestInterceptor(requestInterceptor).build();
mWebApi = restAdapter.create(WebApi.class);

当我在电话上没有互联网的情况下执行相同的请求时,它返回的是:HTTP/1.1 504 Unsatisfiable Request (only-if-cached) OkHttp-Response-Source: NONE

我无法弄清楚我的代码有什么问题,互联网上的所有资源都使用相同的代码!

4

0 回答 0