Android Volley caching with various POST requests

I use Android Volley to cache requests, this works fine when I used GET, but for some reason I switched to using POST. 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"
  • Query 3 -> URL1, POST Data = "Cat = 3"

it can be done with Android Volley

+6
source share
2 answers

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

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

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

when you try to get a cached request, you need to build the cache key in 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(); return temp; } } 

When you build a new query, you can use getCacheKey () to search for a cached query first before placing it in the query queue.

Hope this helps.

+12
source

Also, if you do not want to use one of the existing Request classes, you can follow this code (I use 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 the Mahmoud Fayez answer , here's the generateCacheKeyWithParam() method:

 public static String generateCacheKeyWithParam(String url, Map<String, String> params) { for (Map.Entry<String, String> entry : params.entrySet()) { url += entry.getKey() + "=" + entry.getValue(); } return url; } 
+2
source

Source: https://habr.com/ru/post/976636/


All Articles