0

我有一个从第三方网站下载信息的 AsyncTask。本网站不受我控制。

问题是有时我会在 2 秒内获得此信息,但有时可能需要 30-40 秒。

我知道问题出在网站本身,因为我在网络浏览器的桌面上遇到了同样的问题。

我正在寻找的是一种在操作时间超过一定时间时取消操作并重试的方法。

这是我当前的代码:

protected ArrayList<Card> doInBackground(Void... voids)
{
    Looper.prepare();
    publishProgress("Preparing");
    SomeClass someClass = new SomeClass(this);

    return someClass.downloadInformation();
}
4

1 回答 1

1

您可以尝试为您的 Http 请求设置超时和套接字连接。您会看到此链接:How to set HttpResponse timeout for Android in Java 以了解如何设置它们。

并使用 HttpRequestRetryHandler 来启用自定义异常恢复机制。

来自http://hc.apache.org:“默认情况下,HttpClient 尝试从 I/O 异常中自动恢复。默认的自动恢复机制仅限于少数已知安全的异常。

  • HttpClient 不会尝试从任何逻辑或 HTTP 协议错误(从 HttpException 类派生的错误)中恢复。
  • HttpClient 将自动重试那些假定为幂等的方法。
  • 当 HTTP 请求仍在传输到目标服务器时(即请求尚未完全传输到服务器),HttpClient 将自动重试那些因传输异常而失败的方法。”

例子:

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了解更多详细信息。

于 2013-01-05T14:32:32.797 回答