Android Volley无法为使用OkHttp3作为其传输的特定请求禁用缓存

时间:2016-03-29 05:17:15

标签: android android-volley okhttp okhttp3

我尝试了一些方法来禁用特定排球请求的缓存,但应用程序始终使用缓存数据。我的Feed标头中有header("Cache-Control: no-store,no-cache, must-revalidate");。我从Android Studio启动了多个测试,并且在Logcat中,Feed的时间戳仍然相同。

我在发出请求之前已经添加了stringRequest.setShouldCache(false);并清除了缓存queue.getCache().clear();,但它不起作用。

活动类:

private RequestQueue queue;

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

   /*
    *VolleyStringRequest is basically a class 
    *  that extends StringRequest with some common methods like `getHeaders()`.
    */

    VolleyStringRequest stringRequest = new VolleyStringRequest(Request.Method.GET, url,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        Log.d("note", response);
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        new VolleyErrorListener(context, error);
                    }
                }
        );

        queue = CustomVolleyRequestQueue.getInstance(this.getApplicationContext())
                .getRequestQueue();

         /**************HERE***************/
        queue.getCache().clear();

        stringRequest.setShouldCache(false);


        queue.add(stringRequest);
}

CustomVolleyRequestQueue类:

 public class CustomVolleyRequestQueue {

    private static CustomVolleyRequestQueue mInstance;

    private static Context mCtx;

    private RequestQueue mRequestQueue;

    private CustomVolleyRequestQueue(Context context) {

        mCtx = context;
        mRequestQueue = getRequestQueue();
    }

    public static synchronized CustomVolleyRequestQueue getInstance(Context context) {
        if (mInstance == null) {
            mInstance = new CustomVolleyRequestQueue(context);
        }
        return mInstance;
    }

    public RequestQueue getRequestQueue() {
        if (mRequestQueue == null) {
            Cache cache = new DiskBasedCache(mCtx.getCacheDir(), 10 * 1024 * 1024);
            Network network = new BasicNetwork(new OkHttpStack());
            mRequestQueue = new RequestQueue(cache, network);
            // Don't forget to start the volley request queue
            mRequestQueue.start();
        }
        return mRequestQueue;
    }

}

我还在OKHTTP堆栈类中尝试okHttpRequestBuilder.cacheControl(CacheControl.FORCE_NETWORK);,看看它是否与OkHttp3相关,但它没有什么区别:

public class OkHttpStack implements HttpStack {

    public OkHttpStack() {
    }

    @Override
    public HttpResponse performRequest(com.android.volley.Request<?> request, Map<String, String> additionalHeaders)
        throws IOException, AuthFailureError {

        OkHttpClient.Builder clientBuilder = new OkHttpClient.Builder();
        int timeoutMs = request.getTimeoutMs();

        clientBuilder.connectTimeout(timeoutMs, TimeUnit.MILLISECONDS);
        clientBuilder.readTimeout(timeoutMs, TimeUnit.MILLISECONDS);
        clientBuilder.writeTimeout(timeoutMs, TimeUnit.MILLISECONDS);

        okhttp3.Request.Builder okHttpRequestBuilder = new okhttp3.Request.Builder();
        okHttpRequestBuilder.url(request.getUrl());

        /****************HERE*****************/
        okHttpRequestBuilder.cacheControl(CacheControl.FORCE_NETWORK); 

        Map<String, String> headers = request.getHeaders();
        for(final String name : headers.keySet()) {
            okHttpRequestBuilder.addHeader(name, headers.get(name));
        }

        setConnectionParametersForRequest(okHttpRequestBuilder, request);

        OkHttpClient client = clientBuilder.build();
        okhttp3.Request okHttpRequest = okHttpRequestBuilder.build();
        Call okHttpCall = client.newCall(okHttpRequest);
        Response okHttpResponse = okHttpCall.execute();

        StatusLine responseStatus = new BasicStatusLine(parseProtocol(okHttpResponse.protocol()), okHttpResponse.code(), okHttpResponse.message());
        BasicHttpResponse response = new BasicHttpResponse(responseStatus);
        response.setEntity(entityFromOkHttpResponse(okHttpResponse));

        Headers responseHeaders = okHttpResponse.headers();
        for(int i = 0, len = responseHeaders.size(); i < len; i++) {
            final String name = responseHeaders.name(i), value = responseHeaders.value(i);
            if (name != null) {
                response.addHeader(new BasicHeader(name, value));
            }
        }

        return response;
    }

2 个答案:

答案 0 :(得分:1)

我们可以像下面那样禁用OKhhtp的缓存:

OkHttpClient client = new OkHttpClient();
client.setCache(null);

,这可以帮助您添加请求。

  Volley.newRequestQueue(context.getApplicationContext(), new OkHttpStack(client));

setCache()方法将禁用缓存。我希望这可以帮到你。 THANKYOU

答案 1 :(得分:0)

我们可以从Volley本身禁用缓存

reqObj.setShouldCache(false);

在队列中添加请求之前