OkHttp If-None-Match标头丢失

时间:2016-06-15 20:13:16

标签: java android okhttp etag if-none-match

我正在创建一个Android应用,其中我使用OkHttp网络库作为HTTP客户端。我共享一个缓存大小为10 MB的OkHttpClient实例。流程是:我向服务器发送请求,服务器处理它并生成ETag标头,OkHttp应该在以下对同一URL的请求中连接到If-None-Match标头。问题是请求的标头中缺少If-None-Match标头,因此Response.cacheResponse()始终返回null。所以我的问题是:如何解决这个问题以使用响应缓存?

OkHttpClientSingleton.java:

public class OkHttpClientSingleton
{
   private static OkHttpClientSingleton sOkHttpClientSingleton;

   private OkHttpClient mOkHttpClient;

   public static OkHttpClientSingleton get(Context context)
   {
       if(sOkHttpClientSingleton == null)
       {
           sOkHttpClientSingleton = new OkHttpClientSingleton(context);
       }

       return sOkHttpClientSingleton;
   }

   public OkHttpClientSingleton(Context context)
   {
       int cacheSize = 10 * 1024 * 1024;
       Cache cache = new Cache(context.getCacheDir(), cacheSize);

       mOkHttpClient = new OkHttpClient.Builder()
               .cache(cache)
               .addNetworkInterceptor(new LoggingInterceptor())
               .build();
   }

   public void addRequest(Request request, Callback responseCallback, ProgressDialog progressDialog)
   {
       if(progressDialog != null && !progressDialog.isShowing())
           progressDialog.show();

       mOkHttpClient.newCall(request).enqueue(responseCallback);
   }
}

发送请求代码段:

RequestBody formBody = new FormBody.Builder()
                    .add("data", data)
                    .build();

Request request = new Request.Builder()
                    .url(url)
                    .post(formBody)
                    .build();

Callback responseCallback = new Callback()
{
    @Override
    public void onFailure(Call call, IOException e)
    {
        // Do something
    }

    @Override
    public void onResponse(Call call, Response response)
    {
        dismissProgressDialog();

        Gson gson = new GsonBuilder()
                      .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
                      .create();

        Response cacheResponse = response.cacheResponse(); // Always null

        if(response.isSuccessful())
        {
            if(response.code() == 200)
            {                   
                // Deserialize json using gson
            }
        }
        else
        {
            if(response.code() == 400)
            {
                // Deserialize json using gson
            }
        }
    }
};

OkHttpClientSingleton.get(getContext()).addRequest(request, responseCallback, getProgressDialog());

可以看到来自网络拦截器的两个相同请求的日志here

我在互联网上发现了很多类似的问题,但没有一个能帮助我解决这个问题。

非常感谢任何帮助。

0 个答案:

没有答案