今天在做上传图片的时候,发现一次调用volley请求进行两次上传,经过查资料得知,volley在开始默认两次联网请求,如果后台没有做相应处理,则会发送两次图片,所以造成重复,后来查资料知道通过一个方法可以自己设置联网请求的次数和时间:
RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext()); StringRequest request = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() { @Override public void onResponse(String response) { Toast.makeText(ActivityTuWen.this, "上传成功", Toast.LENGTH_SHORT).show(); finish(); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { } }) { @Override protected Map<String, String> getParams() throws AuthFailureError { // 请求参数 Map<String, String> map = new HashMap<String, String>(); //new 一个Map 参数放到Map中 map.put("user_id", user_id); map.put("title", title); map.put("main_image", mbitmap); map.put("description", description); return map; } }; request.setTag("request"); request.setRetryPolicy(new DefaultRetryPolicy(60000, 0, 1f) { @Override public int getCurrentRetryCount() { /* * Volley默认尝试两次,MAX=1,count=0;count<=MAX;count++;count=2时, * 表示当前已经重复请求两次,就不会再第三次重复请求,从而屏蔽掉Volley的自动重复请求功能; */ return 1; } }); requestQueue.add(request);
这里的这个方法就是设置联网次数和时间的
request.setRetryPolicy(new DefaultRetryPolicy(60000, 0, 1f) { @Override public int getCurrentRetryCount() { return 1; } });
setRetryPolicy()里的参数还可以设置成
<span class="hljs-preprocessor" style="color: rgb(68, 68, 68); box-sizing: border-box; font-family: "Source Code Pro", monospace; font-size: 14px; white-space: pre; background-color: rgba(128, 128, 128, 0.0470588);">setRetryPolicy</span><span style="color: rgb(51, 51, 51); font-family: "Source Code Pro", monospace; font-size: 14px; white-space: pre; background-color: rgba(128, 128, 128, 0.0470588);">(new DefaultRetryPolicy(MY_SOCKET_TIMEOUT_MS, DefaultRetryPolicy</span><span class="hljs-preprocessor" style="color: rgb(68, 68, 68); box-sizing: border-box; font-family: "Source Code Pro", monospace; font-size: 14px; white-space: pre; background-color: rgba(128, 128, 128, 0.0470588);">.DEFAULT</span><span style="color: rgb(51, 51, 51); font-family: "Source Code Pro", monospace; font-size: 14px; white-space: pre; background-color: rgba(128, 128, 128, 0.0470588);">_MAX_RETRIES, DefaultRetryPolicy</span><span class="hljs-preprocessor" style="color: rgb(68, 68, 68); box-sizing: border-box; font-family: "Source Code Pro", monospace; font-size: 14px; white-space: pre; background-color: rgba(128, 128, 128, 0.0470588);">.DEFAULT</span><span style="color: rgb(51, 51, 51); font-family: "Source Code Pro", monospace; font-size: 14px; white-space: pre; background-color: rgba(128, 128, 128, 0.0470588);">_BACKOFF_MULT))</span><span class="hljs-comment" style="color: rgb(136, 0, 0); box-sizing: border-box; font-family: "Source Code Pro", monospace; font-size: 14px; white-space: pre; background-color: rgba(128, 128, 128, 0.0470588);">;</span>