【问题标题】:Should I use android-async-http client in dobackground of Async task?我应该在异步任务的 dobackground 中使用 android-async-http 客户端吗?
【发布时间】:2013-09-27 07:04:45
【问题描述】:

之前我使用的是android的默认Http客户端,然后在http://loopj.com/android-async-http/找到了这个库

当我在 AsyncTask 的 doInBackground(String... args) 中使用这个库时,我注意到 postExecute() 在 android-async-http 返回之前完成。

如果我使用 AsyncHttpClient,我是否应该不使用 AsyncTask。如果我只使用 AsyncHttpClient,有没有办法处理慢速互联网连接或互联网访问超时。

我是android新手,请帮忙!

【问题讨论】:

    标签: android android-asynctask connection-timeout android-async-http


    【解决方案1】:

    正如上述库所暗示的,您可以异步进行网络调用,即不在主线程上,这就是我们实际上使用 asynctask 来避免阻塞主线程的原因。

    所以,如果您使用上述库,则无需使用Asynctask,我相信您永远不会得到NetworkConnectionOnMainThreadException。希望这会有所帮助。

    【讨论】:

    • 问题是如何使用 Asynctask 和默认 http 客户端处理超时?
    • @Prateek 谢谢,它有帮助。我现在使用没有 asynctask 的 AsyncHttpClient。在我覆盖库的所有 onFailure 方法后,它运行良好。
    • @StarWars 很高兴它有帮助。如果你愿意,你可以接受这个答案
    【解决方案2】:

    如果您使用此库,则不必使用 AsyncTask 类来处理请求。

    在您的 Activity 代码中,您可以添加如下内容:

    AsyncHttpClient client = new AsyncHttpClient();
    client.get("http://www.google.com", new AsyncHttpResponseHandler() {
        @Override
        public void onSuccess(String response) {
            System.out.println(response);
        }
    });
    

    这将在后台线程中自动发送请求。在 onSuccess 中,您可以处理响应(类似于 onPostExecute 但我猜它不在 UI 线程上)。

    【讨论】:

      【解决方案3】:

      使用 AsyncHttpClient,您可以通过如下语句轻松处理超时:

      client.setTimeout(5000)
      

      检查所有可用方法的库文档。

      【讨论】:

      • 我在阅读了库的文档后发现了 setTimeout 方法。这个库已经有默认的 10 秒超时,考虑到我的应用程序针对亚洲市场,这没关系,但我不太确定。由于它使用 json api 作为后端,因此数据量不大。您是否建议如上所述的 5 秒超时?
      【解决方案4】:

      首先 asynctask 是同步执行,AsyncHttpClient 是同时执行。不要在异步任务中使用客户端。像这样只使用 AsyncHttpclient。创建通用请求处理程序和侦听器。您还可以为您想要的每个请求创建不同的请求方法,例如 makeRequest,还可以创建不同的侦听器。

      public class RequestHandler{
      
      private static RequestHandler instance;
      
      private AsyncHttpClient client;
      
      private RequestHandler(){
          client = new AsyncHttpClient();
      }
      
      public static RequestHandler getInstance(){
          if(instance == null){
              instance = new RequestHandler();
          }
          return instance;
      }
      
      // You can add more parameters if you need here.
      public void makeRequest(String url, RequestListener listener){
          client.get(url, new AsyncHttpResponseHandler() {
      
              @Override
              public void onStart() {
                  // called before request is started
                  //Some debugging code here
              }
      
              @Override
              public void onSuccess(int statusCode, Header[] headers, byte[] response) {
                  listener.onSuccess(statusCode, headers, response);
              }
      
              @Override
              public void onFailure(int statusCode, Header[] headers, byte[] errorResponse, Throwable exception) {
                   listener.onFailure(statusCode, headers, errorResponse,exception);
                  // called when response HTTP status is "4XX" (eg. 401, 403, 404)
                  //Some debugging code here, show retry dialog, feedback etc. 
              }
      
              @Override
              public void onRetry(int retryNo) {
                   //Some debugging code here-------
      
              }
          });
       }
      }
      
      public interface RequestListener{
      public void onSuccess(int statusCode, Header[] headers, byte[] response);
      public void onFailure(int statusCode, Header[] headers, byte errorResponse, Throwable e);
      }
      

      从活动或片段中提供这样的请求网址

      RequestHandler handler = RequestHandler.getInstance();
      handler.makeRequest("http://www.google.com", new RequestListener(){
       @Override
       public void onSuccess(int statusCode, Header[] headers, byte[] response) {
          // do whatever you want here.       
       }
      });
      

      【讨论】:

        【解决方案5】:

        仅使用 async-http-client 并以这种方式设置超时:

        AsyncHttpClient asyncHttpClient = new AsyncHttpClient();
        
        public MyClassConstructor(){
        
            asyncHttpClient.setConnectTimeout(5000); // default is 10 seconds, minimum is 1 second
            asyncHttpClient.setResponseTimeout(5000); // as above
            asyncHttpClient.setTimeout(5000); // both connection and socket timeout
            asyncHttpClient.setMaxRetriesAndTimeout(1, 100); // times, delay
        

        希望对你有帮助

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2018-10-21
          • 2012-12-17
          • 2016-03-31
          • 2014-09-07
          • 2019-08-17
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多