我正在发出http请求.我在一个平台(android)上,网络操作经常失败,因为网络连接可能不会立即可用.因此,我想在完全失败之前尝试相同的连接N次.想到这样的事情:
DefaultHttpClient mHttp = ...;
public HttpResponse runHttpRequest(HttpRequestBase httpRequest)
throws IOException
{
IOException last = null;
for (int attempt = 0; attempt < 3; attempt++) {
try {
HttpResponse response = mHttpClient.execute(httpRequest);
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == 200) {
return response;
}
} catch (IOException e) {
httpRequest.abort();
last = e;
}
}
throw last;
}
Run Code Online (Sandbox Code Playgroud)
我最担心的是某些状态下的连接在后续重试时无效.换句话说,我是否需要完全重新创建'httpRequest',我应该避免在catch块中调用httpRequest.abort(),并且只在最终失败时调用它吗?
谢谢
文档没有提到会发生这样的事情,尽管你必须尝试它.但更重要的是,您的代码应考虑一些事项......
| 归档时间: |
|
| 查看次数: |
12065 次 |
| 最近记录: |