我正在發出一個http請求。我在一個平臺上(android),網絡操作經常失敗,因爲網絡連接可能不會立即可用。因此,我想在完全失敗之前嘗試相同的連接N次。想到這樣的事情:重試一個http連接
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;
}
我最擔心的是連接處於某種狀態,在隨後的重試中無效。換句話說,我是否需要完全重新創建'httpRequest',是否應該避免在catch塊中調用httpRequest.abort(),並且只在最終失敗時調用它?
感謝