2013-01-05 15 views
0

我有一个从第三方网站下载信息的AsyncTask。本网站不在我的控制之下。如果时间太长,重新启动操作

问题是,有时我在2秒内得到这些信息,但有时可能需要30-40秒。

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

我在找的是一种取消操作的方法,如果它花费的时间超过一定的时间并且再试一次。

这里是我当前的代码:

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

    return someClass.downloadInformation(); 
} 

回答

1

你可以尝试设置为HTTP请求超时和套接字连接。你看到这个链接:How to set HttpResponse timeout for Android in Java 知道如何设置它们。

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

http://hc.apache.org:“在默认情况下的HttpClient尝试从I/O异常自动恢复默认的自动恢复机制仅限于被称为是安全的只有少数例外

  • 的HttpClient将使。没有尝试从任何逻辑或HTTP协议错误(那些从HttpException类派生)恢复。
  • 的HttpClient将自动重试那些被假定为幂等该方法。
  • 的HttpClient将自动重试那些未能与传送异常的方法而H TTP请求仍在传输到目标服务器(即请求尚未完全传输到服务器)“

例:

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

+0

非常感谢你这是真的。 - 非常好,我会尽快测试它:) –

+0

这个答案很完美,非常感谢 –

+0

我很高兴它有帮助! – secretlm