Android Volley Caching with different POST request

2020-07-10 06:17发布

问题:

I am using Android Volley to cache requests this works fine when I was using GET but I switched to use POST for some reasons. Now I want to cache the same URL with different POST data.

  • Request 1 -> URL1, POST Data = "Cat=1"
  • Request 2 -> URL1, POST Data = "Cat=2"
  • Request 3 -> URL1, POST Data = "Cat=3"

is this can be done with Android Volley

回答1:

as the Volley.Request.getCacheKey() returns the URL which in my case is the same; this did not work for me.

Instead I had to override getCacheKey() in my child class to return URL+POST(key=Value)

That way I was able to cache all the POST requests made to the same URL with different POST data.

when you try to retrieve the cached request you need to construct the cache key with the same way.

so here is a snapshot of my code:

public class CustomPostRequest extends Request<String> {
    .
    .
    private Map<String, String> mParams;
    .
    .
    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();// not do another request
        return temp;
    }
}

When ever you construct a new request you can use getCacheKey() to search for the cached request first before putting it in the requests queue.

I hope this helps.



回答2:

Also if you don't want to use one of the existing Request classes you can follow this code (I'm using JsonArrayRequest here, you can use whatever you want)

Map<String, String> params = yourData;

JsonArrayRequest request = new JsonArrayRequest(Request.Method.POST, url, 
    new Response.Listener<JSONArray>() {
        ... Needed codes
    },
    new Response.ErrorListener() {
        ...
    }
){
    @Override
    protected Map<String, String> getParams() throws AuthFailureError {
        return params;
    }
    @Override
    public String getCacheKey() {
        return generateCacheKeyWithParam(super.getCacheKey(), params);
    }
};

and based on Mahmoud Fayez's answer, here the generateCacheKeyWithParam() method:

public static String generateCacheKeyWithParam(String url, Map<String, String> params) {
    StringBuilder urlBuilder = new StringBuilder(url);
    for (Map.Entry<String, String> entry : params.entrySet()) {
      urlBuilder.append(entry.getKey()).append("=").append(entry.getValue());
    }
    url = urlBuilder.toString();
    return url;
}