我有一个从第三方网站下载信息的AsyncTask。这个网站不在我的控制之下。
问题在于,有时我会在2秒内收到此信息,但有时可能需要30-40秒。
我知道问题出在网站本身,因为我在网络浏览器中遇到了同样的问题。
我正在寻找的是一种取消操作的方法,如果花费的时间超过一定时间并再试一次。
这是我目前的代码:
protected ArrayList<Card> doInBackground(Void... voids)
{
Looper.prepare();
publishProgress("Preparing");
SomeClass someClass = new SomeClass(this);
return someClass.downloadInformation();
}
答案 0 :(得分:1)
您可以尝试为Http请求设置超时和套接字连接。您会看到以下链接:How to set HttpResponse timeout for Android in Java 知道如何设置它们。
使用HttpRequestRetryHandler启用自定义异常恢复机制。
来自http://hc.apache.org:“默认情况下,HttpClient会尝试从I / O异常中自动恢复。默认的自动恢复机制仅限于一些已知安全的例外情况。
示例:
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpRequestRetryHandler myRetryHandler = new HttpRequestRetryHandler() {
public boolean retryRequest(
IOException exception,
int executionCount,
HttpContext context) {
if (executionCount >= 5) {
// Do not retry if over max retry count
return false;
}
if (exception instanceof InterruptedIOException) {
// Timeout
return false;
}
if (exception instanceof UnknownHostException) {
// Unknown host
return false;
}
if (exception instanceof SocketTimeoutException) {
//return true to retry
return true;
}
if (exception instanceof ConnectException) {
// Connection refused
return false;
}
if (exception instanceof SSLException) {
// SSL handshake exception
return false;
}
HttpRequest request = (HttpRequest) context.getAttribute(
ExecutionContext.HTTP_REQUEST);
boolean idempotent = !(request instanceof HttpEntityEnclosingRequest);
if (idempotent) {
// Retry if the request is considered idempotent
return true;
}
return false;
}
};
httpclient.setHttpRequestRetryHandler(myRetryHandler);
查看此链接: http://hc.apache.org/httpcomponents-client-ga/tutorial/html/fundamentals.html#d4e292了解更多细节。