Cis*_*azz 184 android timeout android-volley
我使用Android的新Volley框架向我的服务器发出请求.但是在得到回复之前它会超时,尽管它确实有所回应.
我尝试添加此代码:
HttpConnectionParams.setConnectionTimeout(httpParams, 5000);
HttpConnectionParams.setSoTimeout(httpParams, timeoutMs);
Run Code Online (Sandbox Code Playgroud)
在HttpClientStackVolley框架中的一个不同的整数(50000),但它仍然在50秒之前超时.
有没有办法将超时更改为长值?
lar*_*am1 346
请参阅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));
Run Code Online (Sandbox Code Playgroud)
Yak*_*pan 218
要处理Android Volley Timeout,您需要使用 RetryPolicy
RetryPolicy 是一个接口,您需要在超时发生时实现您想要重试特定请求的逻辑.
它涉及这三个参数
对于前者 如果使用这些值创建RetryPolicy
超时 - 3000毫秒,重试次数 - 2,后退乘数 - 2.0
重试尝试1:
重试尝试2:
因此,在重试尝试2结束时,如果仍然发生Socket Timeout,则Volley将TimeoutError在您的UI Error响应处理程序中抛出一个.
//Set a retry policy in case of SocketTimeout & ConnectionTimeout Exceptions.
//Volley does retry for you if you have specified the policy.
jsonObjRequest.setRetryPolicy(new DefaultRetryPolicy(5000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
Run Code Online (Sandbox Code Playgroud)
And*_*son 23
只是为了贡献我的方法.正如已经回答的那样,RetryPolicy是要走的路.但是,如果您需要的策略与所有请求的默认值不同,则可以在基本Request类中设置该策略,因此您无需为请求的所有实例设置策略.
像这样的东西:
public class BaseRequest<T> extends Request<T> {
public BaseRequest(int method, String url, Response.ErrorListener listener) {
super(method, url, listener);
setRetryPolicy(getMyOwnDefaultRetryPolicy());
}
}
Run Code Online (Sandbox Code Playgroud)
在我的情况下,我有一个从这个BaseRequest扩展的GsonRequest,因此我不会冒失去为特定请求设置策略的风险,如果某些特定请求需要,您仍然可以覆盖它.
小智 11
/**
* @param request
* @param <T>
*/
public <T> void addToRequestQueue(Request<T> request) {
request.setRetryPolicy(new DefaultRetryPolicy(
MY_SOCKET_TIMEOUT_MS,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
getRequestQueue().add(request);
}
Run Code Online (Sandbox Code Playgroud)
小智 7
req.setRetryPolicy(new DefaultRetryPolicy(
MY_SOCKET_TIMEOUT_MS,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
Run Code Online (Sandbox Code Playgroud)
您可以设置MY_SOCKET_TIMEOUT_MS为100.无论您想要设置为什么,都以毫秒为单位.DEFAULT_MAX_RETRIES可以是0默认值是1.
int MY_SOCKET_TIMEOUT_MS=500;
stringRequest.setRetryPolicy(new DefaultRetryPolicy(
MY_SOCKET_TIMEOUT_MS,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
145267 次 |
| 最近记录: |