本文介绍了改造 - Okhttp客户如何缓存响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想缓存由改造(V 1.9.0)与OkHttp(2.3.0)进行HTTP调用的响应。它总是让网络通话,如果我尽量让不上网的电话,然后的java.net.UnknownHostException

I'm trying to cache the response of http calls done by Retrofit(v 1.9.0) with OkHttp(2.3.0). It always made the network calls if I try to make a call without internet then java.net.UnknownHostException.

RestClient

public class RestClient {
public static final String BASE_URL = "http://something.example.net/JSONService";
private com.ucc.application.rest.ApiService apiService;

public RestClient() {
    Gson gson = new GsonBuilder()
            .setDateFormat("yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'SSS'Z'")
            .create();

    RequestInterceptor requestInterceptor = new RequestInterceptor() {

        @Override
        public void intercept(RequestFacade request) {
            request.addHeader("Accept", "application/json");
            int maxAge = 60 * 60;
            request.addHeader("Cache-Control", "public, max-age=" + maxAge);
        }
    };

    RestAdapter restAdapter = new RestAdapter.Builder()
            .setLogLevel(RestAdapter.LogLevel.FULL)
            .setEndpoint(BASE_URL)
            .setClient(new OkClient(OkHttpSingleTonClass.getOkHttpClient()))
            .setConverter(new GsonConverter(gson))
            .setRequestInterceptor(requestInterceptor)
            .build();

    apiService = restAdapter.create(com.ucc.application.rest.ApiService.class);
}

public com.ucc.application.rest.ApiService getApiService() {
    return apiService;
}

}

OkHttpSingleTonClass

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;
}

}

MyActivity

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.

    }

我跟着这个。但我不能管理工作。它只需从服务器击​​中。什么我OI做错了什么?

I followed this. But I can't manage to work. Its simply hitting from the server. What am oi doing wrong?

推荐答案

根据改造 1.9.0 ,它使用 OkClient 没有缓存的支持。我们通过广场 OkHttpClient 库使用 OkHttpClient 实例。

As per Retrofit 1.9.0 which uses OkClient does not have Caching support. We have to use OkHttpClient instance by Square OkHttpClient library.

您可以通过

编译com.squareup.okhttp:okhttp:2.3.0

在家居改造缓存由响应头像

Before everything retrofit caches by response headers like

缓存控制:最大年龄= 120,仅-如果缓存,最大-陈旧

** 120秒。

您可以阅读更多有关页眉这里

You can read more about headers here.

缓存头是由服务器响应主要指示。 试图实现在服务器缓存头。 如果你没有一个选项,是改造了它。

Caching headers are mostly instructed by server response. Try to implement cache headers in servers. If you don't have an option, yes retrofit has it.

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实例

okHttpClient.networkInterceptors().add(REWRITE_CACHE_CONTROL_INTERCEPTOR);

和最后加上OkHttpClient到RestAdapter

RestAdapter.setClient(New OkClient(okHttpClient));

和你可以通过<一个href="https://docs.google.com/$p$psentation/d/1eJa0gBZLpZRQ5vjW-eqLyekEgB54n4fQ1N4jDcgMZ1E/edit?usp=sharing">this滑动更多的参考。

And you can go through this slide for more reference.

这篇关于改造 - Okhttp客户如何缓存响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-05 19:11