简体   繁体   English

Android okhttp获取缓存响应

[英]Android okhttp get cache response

i'am not an expert handling with http but what is was trying to accomplish is: 我不是使用http处理的专家,但是尝试完成的工作是:

If the response is in cache return cache if not return network response simple as that. 如果响应在高速缓存中,则返回高速缓存,如果不返回,则网络响应如此简单。

But the problem is the the response code is always 504 but i'am sure that it's cached, so for my understanding it should return != 504, the code is in the "doGetRequest" method. 但是问题是响应代码始终为504,但我确定它已被缓存,因此据我所知,它应返回!= 504,该代码位于“ doGetRequest”方法中。

My okhttp client: 我的okhttp客户端:

public class RestAsyncHttpClient {

/* Constants */
private static final String TAG = "RestAsyncHttpClient";
private static long HTTP_CACHE_SIZE = 10 * 1024 * 1024; // 10 MiB
private static final String DISK_CACHE_SUBDIR = "cacheApi";

/* Properties */
private static OkHttpClient mHttpClient;
private static Cache cache;
private static RestAsyncHttpClient instance = null;
private Context context;

public static RestAsyncHttpClient getInstance() {
    if (instance == null) {
        instance = new RestAsyncHttpClient();
    }
    return instance;
}

/**
 * Initialize HttpClient
 */
public void initialize(Context context) {
    setContext(context);

    mHttpClient = new OkHttpClient();

    configureSslSocketFactory();

    configureCache();

    configureTimeouts();
}

private void setContext(Context context) {
    this.context = context;
}

private void configureSslSocketFactory() {
    mHttpClient.setSslSocketFactory(HttpsURLConnection.getDefaultSSLSocketFactory());
}

public static void doGetRequest(String url, Callback callback) throws IOException {
    Request cachedRequest = new Request.Builder()
            .cacheControl(new CacheControl.Builder().onlyIfCached().build())
            .url(url)
            .build();
    Response forceCacheResponse = mHttpClient.newCall(cachedRequest).execute();
    if (forceCacheResponse.code() != 504) {
        // The resource was cached! Show it.
        callback.onResponse(forceCacheResponse);

    } else {
        Request networkRequest = new Request.Builder().url(url).build();
        mHttpClient.newCall(networkRequest).enqueue(callback);
    }
}

private void configureCache() {
    if (cache == null)
        cache = createHttpClientCache(context);

    mHttpClient.setCache(cache);
}

private static Cache createHttpClientCache(Context context) {
    try {
        File cacheDir = context.getDir("cache_api", Context.MODE_PRIVATE);
        return new Cache(cacheDir, HTTP_CACHE_SIZE);

    } catch (IOException exp) {
        LogHelper.error(TAG, "Couldn't create http cache because of IO problem.", exp);
        return null;
    }
}

private void configureTimeouts() {
    mHttpClient.setConnectTimeout(10, TimeUnit.SECONDS);
    mHttpClient.setWriteTimeout(35, TimeUnit.SECONDS);
    mHttpClient.setReadTimeout(35, TimeUnit.SECONDS);
}

} }

My cache is being filled so it should read from cache when no connection available. 我的缓存已满,因此在没有可用连接时应从缓存中读取。 缓存文件

Response Headers from server: 来自服务器的响应头:

  • Connection:close 连接:关闭
  • Content-Type:application/json; 内容类型:应用/ JSON; charset=iso-8859-1 字符集= ISO-8859-1
  • Date:Mon, 23 Mar 2015 11:04:44 GMT 日期:2015年3月23日星期一11:04:44 GMT
  • Server:Apache 服务器:Apache
  • Transfer-Encoding:chunked 传输编码:分块
  • X-Powered-By:Servlet/2.5 JSP/2.1 X-Powered-By:Servlet / 2.5 JSP / 2.1

Request Headers: 请求标头:

  • Accept:text/html,application/xhtml+xml,application/xml;q=0.9,image/webp, / ;q=0.8 接受:text / html,application / xhtml + xml,application / xml; q = 0.9,image / webp, / ; q = 0.8
  • Accept-Encoding:gzip, deflate, sdch 接受编码:gzip,deflate,sdch
  • Accept-Language:pt-PT,pt;q=0.8,en-US;q=0.6,en;q=0.4,fr;q=0.2 接受语言:PT-PT,PT; Q = 0.8,的en-US; Q = 0.6,连接; Q = 0.4,FR,Q = 0.2
  • Cache-Control:max-age=0 缓存控制:最大年龄= 0
  • Connection:keep-alive 连接:保持活跃
  • Host:cantShare:448 主持人:cantShare:448
  • User-Agent:Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.101 Safari/537.36 用户代理:Mozilla / 5.0(Windows NT 6.3; WOW64)AppleWebKit / 537.36(KHTML,例如Gecko)Chrome / 41.0.2272.101 Safari / 537.36

When you get a response back, you need to read it entirely, otherwise it won't be cached. 当您收到响应时,您需要完整地阅读它,否则它不会被缓存。 This is because OkHttp only commits the response to the cache when you finish reading its body. 这是因为OkHttp仅在完成读取其主体后才将响应提交到缓存。

You don't need the special case for 504. Just make the request regularly, and it'll use the cache if it can. 您不需要504的特殊情况。只需定期发出请求,它会使用缓存。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM