Java 正在重试http连接
我正在发出http请求。我在一个android平台上,网络操作经常会失败,因为网络连接可能不会立即可用。因此,在完全失败之前,我想尝试相同的连接N次。我在想这样的事情:Java 正在重试http连接,java,android,Java,Android,我正在发出http请求。我在一个android平台上,网络操作经常会失败,因为网络连接可能不会立即可用。因此,在完全失败之前,我想尝试相同的连接N次。我在想这样的事情: DefaultHttpClient mHttp = ...; public HttpResponse runHttpRequest(HttpRequestBase httpRequest) throws IOException { IOException last = null; for (int a
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;
}
DefaultHttpClient mHttp=。。。;
公共HttpResponse runHttpRequest(HttpRequestBase httpRequest)
抛出IOException
{
IOException last=null;
for(int-trunt=0;trunt<3;trunt++){
试一试{
HttpResponse response=mHttpClient.execute(httpRequest);
int statusCode=response.getStatusLine().getStatusCode();
如果(状态代码==200){
返回响应;
}
}捕获(IOE异常){
httpRequest.abort();
last=e;
}
}
扔到最后;
}
我最担心的是连接处于某种状态,在随后的重试中无效。换句话说,我是否需要完全重新创建“httpRequest”,我是否应该避免在catch块中调用httpRequest.abort(),而只在最终失败时调用它
谢谢文档中没有提到会发生这种情况,尽管您必须尝试一下。更重要的是,有一些事情你应该考虑你的代码…
A看来这可能会有帮助 我建议使用AOP和Java注释(我是开发人员):
@RetryOnFailure(attempts = 3, delay = 5)
public String load(URL url) {
return url.openConnection().getContent();
}