Android Volley Caching使用相同的url但不同的帖子参数

时间:2016-07-19 14:09:08

标签: android android-layout

我有两个不同参数的api调用,而iam使用volley进行网络调用。

当iam尝试进行缓存时,响应为两个调用获取相同的数据。

我尝试使用CacheRequest和Custompostrequet

public class CacheRequest extends Request<NetworkResponse> {
private final Response.Listener<NetworkResponse> mListener;
private final Response.ErrorListener mErrorListener;

public CacheRequest(int method, String url, Response.Listener<NetworkResponse> listener, Response.ErrorListener errorListener) {
    super(method, url, errorListener);
    this.mListener = listener;
    this.mErrorListener = errorListener;
}


@Override
protected Response<NetworkResponse> parseNetworkResponse(NetworkResponse response) {
    Cache.Entry cacheEntry = HttpHeaderParser.parseCacheHeaders(response);
    if (cacheEntry == null) {
        cacheEntry = new Cache.Entry();
    }
    final long cacheHitButRefreshed = 3 * 60 * 1000; // in 3 minutes cache will be hit, but also refreshed on background
    final long cacheExpired = 24 * 60 * 60 * 1000; // in 24 hours this cache entry expires completely
    long now = System.currentTimeMillis();
    final long softExpire = now + cacheHitButRefreshed;
    final long ttl = now + cacheExpired;
    cacheEntry.data = response.data;
    cacheEntry.softTtl = softExpire;
    cacheEntry.ttl = ttl;
    String headerValue;
    headerValue = response.headers.get("Date");
    if (headerValue != null) {
        cacheEntry.serverDate = HttpHeaderParser.parseDateAsEpoch(headerValue);
    }
    headerValue = response.headers.get("Last-Modified");
    if (headerValue != null) {
        cacheEntry.lastModified = HttpHeaderParser.parseDateAsEpoch(headerValue);
    }
    cacheEntry.responseHeaders = response.headers;
    return Response.success(response, cacheEntry);
}

@Override
protected void deliverResponse(NetworkResponse response) {
    mListener.onResponse(response);
}

@Override
protected VolleyError parseNetworkError(VolleyError volleyError) {
    return super.parseNetworkError(volleyError);
}

@Override
public void deliverError(VolleyError error) {
    mErrorListener.onErrorResponse(error);
}

}

公共抽象类CustomPostRequest扩展了Request {

private Map<String, String> mParams;

public CustomPostRequest(int method, String url, Response.ErrorListener listener) {
    super(method, url, listener);
}

public void SetPostParam(String strParam, String strValue) {
    mParams.put(strParam, strValue);
}

@Override
public Map<String, String> getParams() {
    return mParams;
}

@Override
public String getCacheKey() {
    String temp = super.getCacheKey();
    for (Map.Entry<String, String> entry : mParams.entrySet())
        temp += entry.getKey() + "=" + entry.getValue();
    return temp;
}

}

我使用的两个调用是::

    private void makeJsonObjReqtoGetHealthTips() {

    mHlthTipProgressBar.setVisibility(View.VISIBLE);

     StringRequest sr = new StringRequest(CustomPostRequest.Method.POST, getResources().getString(R.string.root_url) + "data", new Response.Listener<String>() {
  //  CacheRequest cacheRequest = new CacheRequest(CustomPostRequest.Method.POST, getResources().getString(R.string.root_url) + "articles", new Response.Listener<NetworkResponse>() {
        @Override
        public void onResponse(String response) {
               // final String jsonString = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
                Constants.showLog(TAG, response);
                mHlthTipProgressBar.setVisibility(View.GONE);
                parseHealthTips(response);
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            VolleyLog.d(TAG, "Error: " + error.getMessage());

            mHlthTipProgressBar.setVisibility(View.GONE);
            Constants.showCustomAlertDialog(getActivity(), VolleyErrorHelper.getMessage(error, getActivity()), "Ok");
        }
    }) {

        @Override
        public Priority getPriority() {
            return Priority.LOW;
        }


        @Override
        protected Map<String, String> getParams() {
            Map<String, String> params = new HashMap<String, String>();
            params.put("filter[category_name]", "tips");
            params.put("include_tips", "Yes");
            params.put("filter[posts_per_page]", "10");
            params.put("desc_chars_limit", "500");
            return params;
        }

        @Override
        public Map<String, String> getHeaders() throws AuthFailureError {
            Map<String, String> headers = new HashMap<String, String>();
            headers.put("Content-Type", "application/x-www-form-urlencoded");
            headers.put("customer", shrf.getString("customer_id", ""));
            return headers;
        }
    };


    sr.setRetryPolicy(new DefaultRetryPolicy(
            30000,
            DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
            DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));

    Application.getInstance().addToRequestQueue(sr, HEALTH_TIPS_TAG);

    // Cancelling request
    // ApplicationController.getInstance().getRequestQueue().cancelAll(tag_json_obj);
}

private void makeJsonObjReqtoGetFeaturedArticles() {
    mFeaturedProgressBar.setVisibility(View.VISIBLE);

    CacheRequest cacheRequest = new CacheRequest(CustomPostRequest.Method.POST, getResources().getString(R.string.root_url) + "data", new Response.Listener<NetworkResponse>() {
        @Override
        public void onResponse(NetworkResponse response) {
            try {
                final String jsonString = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
                mFeaturedProgressBar.setVisibility(View.GONE);
                Constants.showLog(TAG, response + "");
                //  String responseJson = response.toString();
                parseFeaturedArticles(jsonString);
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            VolleyLog.d(TAG, "Error: " + error.getMessage());
            mFeaturedProgressBar.setVisibility(View.GONE);
            Constants.showCustomAlertDialog(getActivity(), VolleyErrorHelper.getMessage(error, getActivity()), "Ok");
            //Log.d(TAG, "" + error.getMessage() + "," + error.toString());
        }
    }) {
        @Override
        public Priority getPriority() {
            return Priority.IMMEDIATE;
        }

        @Override
        protected Map<String, String> getParams() {
            Map<String, String> params = new HashMap<String, String>();
            params.put("filter[posts_per_page]", "5");
            params.put("filter[featured]", "Yes");
            return params;
        }

        @Override
        public Map<String, String> getHeaders() throws AuthFailureError {
            Map<String, String> headers = new HashMap<String, String>();
            headers.put("Content-Type", "application/x-www-form-urlencoded");
            headers.put("customer", shrf.getString("customer_id", ""));
            return headers;
        }

    };

    cacheRequest.setRetryPolicy(new DefaultRetryPolicy(
            30000,
            DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
            DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));

    Application.getInstance().addToRequestQueue(cacheRequest, FEATURED_TAG);

    // Cancelling request
    // ApplicationController.getInstance().getRequestQueue().cancelAll(tag_json_obj);
}

请帮我解决这个问题。

0 个答案:

没有答案