Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/367.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/227.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 改装-Okhttp客户端如何缓存响应_Java_Android_Retrofit_Cache Control_Okhttp - Fatal编程技术网

Java 改装-Okhttp客户端如何缓存响应

Java 改装-Okhttp客户端如何缓存响应,java,android,retrofit,cache-control,okhttp,Java,Android,Retrofit,Cache Control,Okhttp,我试图缓存通过使用OkHttp(2.3.0)对(v1.9.0)进行改造而完成的http调用的响应。如果我尝试在没有internet的情况下拨打电话,它总是会拨打网络电话,然后java.net.UnknownHostException RestClient OkHttpSingleTonClass 我的活动 我跟着。但我无法工作。它只是从服务器上点击。我做错了什么?根据改型1.9.0使用的OkClient不支持缓存。我们必须使用SquareOkHttpClient实例OkHttpClient库 您

我试图缓存通过使用OkHttp(2.3.0)对(v1.9.0)进行改造而完成的http调用的响应。如果我尝试在没有internet的情况下拨打电话,它总是会拨打网络电话,然后
java.net.UnknownHostException

RestClient

OkHttpSingleTonClass

我的活动


我跟着。但我无法工作。它只是从服务器上点击。我做错了什么?

根据改型
1.9.0
使用的
OkClient
不支持缓存。我们必须使用Square
OkHttpClient
实例
OkHttpClient

您可以通过
compile'com.squareup.okhttp:okhttp:2.3.0'

在一切发生之前,通过响应头(如

Cache Control:max age=120,仅当已缓存时,max stale

**120是秒

您可以阅读更多关于标题的信息

缓存头主要由服务器响应指示。尝试在服务器中实现缓存头。如果你没有选择,是的,改装有

private static final Interceptor REWRITE_CACHE_CONTROL_INTERCEPTOR = new Interceptor() {
    @Override
    public Response intercept(Chain chain) throws IOException {
        Response originalResponse = chain.proceed(chain.request());
        return originalResponse.newBuilder()
                .header("Cache-Control", String.format("max-age=%d, only-if-cached, max-stale=%d", 120, 0))
                .build();
    }
};
缓存位置:

将拦截器添加到OkHttpClient实例:

最后,将OkHttpClient添加到RestAdapter:


您可以浏览幻灯片以获取更多参考。

您可以测试和吗?我对Pragma头有一些问题,最后找到了一种方法,可以删除该头值。这里有一个演示项目,它将所有需要它的人的概念集合在一起。
public class OkHttpSingleTonClass {


private static OkHttpClient okHttpClient;

private OkHttpSingleTonClass() {
}

public static OkHttpClient getOkHttpClient() {
    if (okHttpClient == null) {
        okHttpClient = new OkHttpClient();
        createCacheForOkHTTP();
    }
    return okHttpClient;
}

private static void createCacheForOkHTTP() {
    Cache cache = null;
    cache = new Cache(getDirectory(), 1024 * 1024 * 10);
    okHttpClient.setCache(cache);
}

public static File getDirectory() {
    final File root = new File(Environment.getExternalStorageDirectory() + File.separator + "UCC" + File.separator);
    root.mkdirs();
    final String fname = UserUtil.CACHE_FILE_NAME;
    final File sdImageMainDirectory = new File(root, fname);
    return sdImageMainDirectory;
}

}
Request request = new Request.Builder()
            .cacheControl(new CacheControl.Builder()
                    .onlyIfCached()
                    .maxAge(60 * 60, TimeUnit.SECONDS)
                    .build())
            .url(RestClient.BASE_URL + Constants.GET_ABOUT_US_COLLECTION + "?userid=59e41b02-35ed-4962-8517-2668b5e8dae3&languageid=488d8f13-ef7d-4a3a-9516-0e0d24cbc720")
            .build();
    Log.d("url_request", RestClient.BASE_URL + Constants.GET_ABOUT_US_COLLECTION + "/?userid=10");
    com.squareup.okhttp.Response forceCacheResponse = null;
    try {
        forceCacheResponse = OkHttpSingleTonClass.getOkHttpClient().newCall(request).execute();
    } catch (IOException e) {
        e.printStackTrace();
    }
    if (forceCacheResponse.code() != 504) {
        // The resource was cached! Show it.
        Log.d("From", "Local");
        Toast.makeText(AboutUs.this, "Local", Toast.LENGTH_SHORT).show();
    } else {
        // The resource was not cached.
        Log.d("From", "Network");
        Toast.makeText(AboutUs.this, "Network", Toast.LENGTH_SHORT).show();
        getAbouUsDetails();//This will use the Apiservice interface to hit the server.

    } 
private static final Interceptor REWRITE_CACHE_CONTROL_INTERCEPTOR = new Interceptor() {
    @Override
    public Response intercept(Chain chain) throws IOException {
        Response originalResponse = chain.proceed(chain.request());
        return originalResponse.newBuilder()
                .header("Cache-Control", String.format("max-age=%d, only-if-cached, max-stale=%d", 120, 0))
                .build();
    }
};
private static void createCacheForOkHTTP() {
    Cache cache = null;
    cache = new Cache(getDirectory(), 1024 * 1024 * 10);
    okHttpClient.setCache(cache);
}

// returns the file to store cached details
private File getDirectory() {
    return new File(“location”);
}
okHttpClient.networkInterceptors().add(REWRITE_CACHE_CONTROL_INTERCEPTOR);
RestAdapter.setClient(new OkClient(okHttpClient));