gpt4 book ai didi

java - 改造 - Okhttp 客户端如何缓存响应

转载 作者:IT老高 更新时间:2023-10-28 20:51:10 32 4
gpt4 key购买 nike

我正在尝试使用 OkHttp(2.3.0) 缓存 Retrofit(v 1.9.0) 完成的 http 调用的响应。如果我尝试在没有互联网的情况下调用电话然后 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;
}

}

我的 Activity

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.

}

我关注了this .但我无法工作。它只是从服务器上击中。我做错了什么?

最佳答案

根据 Retrofit 1.9.0 使用 OkClient 没有缓存支持。我们必须使用 Square OkHttpClient 库中的 OkHttpClient 实例。

可以通过compile 'com.squareup.okhttp:okhttp:2.3.0'进行编译

在一切改造缓存之前,响应 header 如

Cache-Control:max-age=120,only-if-cached,max-stale

** 120 是秒。

您可以阅读有关标题的更多信息 here.

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

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

你可以通过this幻灯片以获取更多引用。

关于java - 改造 - Okhttp 客户端如何缓存响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29119253/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com