【发布时间】:2018-06-16 01:03:47
【问题描述】:
我面临的问题是我的POST 请求参数在第一次后不会发送到服务器。我知道Volley 正在使用缓存机制进行响应,但在我的情况下,我的请求参数值可以在运行时更改,因为我在Recyclerview 中使用分页。
所以我的问题是我怎样才能每次都发送 Post 请求参数并且不会松动 volley 的缓存机制。
我尝试过使用下面的方法并完成我的工作(每次都调用 getParams()).. 但它会丢失缓存响应,我不希望这样。
requestQueue.getCache().clear();
stringRequest.setShouldCache(false);
还搜索了谷歌和下面的链接,但找不到任何合适的解决方案。以下是SO链接
- Volley not calling getParams() for second time
- Volley not calling getParams()
- Android volley does not calling getParams in POST request
- Volley not calling getParams() for standard POST request
下面是我的代码:
StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
Log.e("RES", response);
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.setDateFormat("M/d/yy hh:mm a"); //Format of our JSON dates
Gson gson = gsonBuilder.create();
NewsFeedPOJO resultObj = (NewsFeedPOJO) gson.fromJson(response, (Class) NewsFeedPOJO.class);
inCurrPage = Integer.parseInt(resultObj.getPagination().getCurrent_page());
inTotalPage = Integer.parseInt(resultObj.getPagination().getTotal_pages());
inCurrPage++;
arrayList.addAll(resultObj.getNewsFeedList());
if (isFtym) {
isFtym = false;
layoutManager = new LinearLayoutManager(MainActivity.this);
rcNewsFeed.setLayoutManager(layoutManager);
adapter = new NewsFeedAdapter(MainActivity.this, arrayList);
rcNewsFeed.setAdapter(adapter);
} else {
adapter.notifyItemInserted(arrayList.size());
adapter.notifyDataSetChanged();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
}
}) {
@Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> map = new HashMap<>();
map.put("user_id", "188");
if (inCurrPage == 0)
map.put("page", "1");
else {
map.put("page", "" + inCurrPage);
}
Log.e("RES", inCurrPage + " PARA");
return map;
}
};
//RequestQueue requestQueue = Volley.newRequestQueue(MainActivity.this);
//requestQueue.add(stringRequest);
//requestQueue.getCache().clear();
//AppController.getInstance().addToRequestQueue(stringRequest);
// stringRequest.setShouldCache(false);
VolleySingleton.getInstance(this).addToRequestQueue(stringRequest);
使用下面的 Volley Dependency。
compile 'com.android.volley:volley:1.1.0'
如果需要更多信息,请告诉我。提前致谢。您的努力将不胜感激。
【问题讨论】:
-
不确定 Volley,但 square.github.io/retrofit 确实可以处理这些情况。它比 Volley 更加巩固和高效。查看这些比较instructure.github.io/blog/2013/12/09/volley-vs-retrofit
-
如果您想检索下一页,您应该向队列中添加一个新请求。不重用现有请求
-
您是否尝试过以下链接。 stackoverflow.com/q/36288500/4140857
-
你使用过request.setRetryPolicy(new DefaultRetryPolicy(SERVER_TIMEOUT, MAX_RETRY, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
-
其中 MaxRetry 为 0,1 或任何您想要重复调用的值,默认为 1
标签: android caching post android-volley