如果连接或套接字超时,我将使用HttpClient
和HttpRequestRetryHandler
重试。因此,我关闭了连接,并调用API,希望调用HttpRequestRetryHandler
。但是它没有被调用。甚至没有输入方法。
代码:
HttpClient client = new DefaultHttpClient();
client.getParams().setIntParameter(
HttpConnectionParams.CONNECTION_TIMEOUT,
CONNECTION_TIMEOUT * 1000);
client.getParams().setIntParameter(HttpConnectionParams.SO_TIMEOUT,
SOCKET_TIMEOUT * 1000);
// Retry handler which handles request retry
HttpRequestRetryHandler requestRetryHandler = new HttpRequestRetryHandler() {
@Override
public boolean retryRequest(IOException exception,
int executionCount, HttpContext context) {
if ((exception instanceof ConnectTimeoutException || exception instanceof SocketTimeoutException)
&& executionCount <= MAX_TRIES) {
Log.d(TAG, "Retrying connection.");
return true;
}
return false;
}
};
((AbstractHttpClient) client)
.setHttpRequestRetryHandler(requestRetryHandler);
但是同时,我尝试捕获如下所示的
ConnectTimeoutException
,并且执行确实输入了ConnectTimeoutException
的catch块。try {
// Making API request
} catch (ConnectTimeoutException ce) {
// Execution enters here
ce.printStackTrace();
}
我的avd在android版本的果冻豆上运行。
代码有什么问题吗?
打印ConnectTimeoutException跟踪时的Logcat:
最佳答案
我遇到了同样的问题,我想分享自己的解决方案(为我工作)。
为了节省系统资源,通常将许多HTTP服务器配置为在一段时间不活动后删除持久连接,以节省系统资源,而通常不会通知客户端。见HttpClient Connection keep alive strategy
如果服务器断开连接,则HttpRequestRetryHandler将没有机会再试一次(执行此操作)。
所以我以这种方式解决了:
实施了自定义连接保持活动策略
mHttpClient.setKeepAliveStrategy(new ConnectionKeepAliveStrategy() {
// Honor 'keep-alive' header
HeaderElementIterator it = new BasicHeaderElementIterator(
response.headerIterator(HTTP.CONN_KEEP_ALIVE));
while (it.hasNext()) {
HeaderElement he = it.nextElement();
String param = he.getName();
String value = he.getValue();
if (value != null && param.equalsIgnoreCase("timeout")) {
try { return Long.parseLong(value) * 1000; }
catch(NumberFormatException ignore) { }
}
}
......
//.Keep Alive for 30 secs
return 30 * 1000;
}
});
然后,我实现了自定义重试处理程序:
HttpRequestRetryHandler retryHandler = new HttpRequestRetryHandler() {
public boolean retryRequest(IOException exception,
int executionCount,
HttpContext context) {
// retry a max of 5 times
if (executionCount >= 5) return false;
if (exception instanceof NoHttpResponseException) {
// Retry if the server dropped connection on us
return true;
}
//.TODO your custom logic...
Boolean b = (Boolean)
context.getAttribute(ExecutionContext.HTTP_REQ_SENT);
boolean sent = (b != null && b.booleanValue());
if (!sent) {
// Retry if the request has not been sent fully or
// if it's OK to retry methods that have been sent
return true;
}
// otherwise do not retry
return false;
}
};
mHttpClient.setHttpRequestRetryHandler(retryHandler);