我使用Android的新Volley框架向我的服务器发出请求。但是它在得到响应之前会超时,尽管它确实会响应。
我尝试添加以下代码:
HttpConnectionParams.setConnectionTimeout(httpParams, 5000);
HttpConnectionParams.setSoTimeout(httpParams, timeoutMs);
在Volley框架的HttpClientStack中调用一个不同的整数(50000),但是它仍然在50秒前超时。
是否有办法将超时更改为较长的值?
参见Request.setRetryPolicy()和DefaultRetryPolicy的构造函数,例如:
JsonObjectRequest myRequest = new JsonObjectRequest(Method.GET,
url, null,
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
Log.d(TAG, response.toString());
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.d(TAG, "Error: " + error.getMessage());
}
});
myRequest.setRetryPolicy(new DefaultRetryPolicy(
MY_SOCKET_TIMEOUT_MS,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
参见Request.setRetryPolicy()和DefaultRetryPolicy的构造函数,例如:
JsonObjectRequest myRequest = new JsonObjectRequest(Method.GET,
url, null,
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
Log.d(TAG, response.toString());
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.d(TAG, "Error: " + error.getMessage());
}
});
myRequest.setRetryPolicy(new DefaultRetryPolicy(
MY_SOCKET_TIMEOUT_MS,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
如果以上所有解决方案都不适合您,请选择其他解决方案
默认情况下,Volley为setConnectionTimeout()和setReadTimeout()设置的timeout值与RetryPolicy相同。在我的情况下,Volley抛出大数据块超时异常见:
com.android.volley.toolbox.HurlStack.openConnection().
我的解决方案是创建一个类,它扩展HttpStack与我自己的setReadTimeout()策略。然后在创建RequestQueue时使用它,如下所示:
Volley.newRequestQueue(mContext.getApplicationContext(), new MyHurlStack())