【问题标题】:Android HttpClient SLOWAndroid HttpClient 慢
【发布时间】:2023-03-30 02:10:01
【问题描述】:

我目前正在开发一个包含 HTML 代码下载功能的 android 应用程序。但是,通过 HttpClient 的执行速度非常慢,通过手机浏览器在 1 或 2 秒内加载的页面大约需要 12 秒。我已经尝试过使用 HttpURLConnection,但它会在大致相同的时间下载代码。你们会建议我改变什么?

public class Downloader extends AsyncTask<String, Void, String> 
{

 protected String doInBackground(String... params) 
 {
    String url = params[0];
    String htmlcode = "FAIL";


        try{

            Log.i("METAMETER","DL: INITIALIZING");
            HttpClient client = new DefaultHttpClient();            
            HttpGet request = new HttpGet(url);
            HttpParams httpParameters = client.getParams();
            HttpConnectionParams.setConnectionTimeout(httpParameters, 1000);
            HttpConnectionParams.setSoTimeout(httpParameters, 1000);

            Log.i("METAMETER","DL: EXECUTING");
            HttpResponse response = client.execute(request);
             //Apparently the step above takes about 12 seconds for a page which only takes 1-2 seconds via browser
            Log.i("METAMETER","DL: WRITING");
            htmlcode = EntityUtils.toString(response.getEntity());


         }catch (Exception e){htmlcode = "EXCEPTION";}
        Log.i("METAMETER","DL: DONE");
  return htmlcode;
  }        
}

【问题讨论】:

  • 我建议您使用 Traceview 并准确确定问题所在。
  • 好的,我刚第一次使用Traceview,你想知道什么?
  • 我可以看到,在 AsyncTask 开始工作之前,有大约 9 秒的间隔。在此期间,任何地方都没有活动。之后,AsyncTask 工作 1.5 秒。但是,这里也有很多小的差距。
  • “我可以看到,在 AsyncTask 开始工作之前有大约 9 秒的间隔”——这表明您的问题不在此代码中,而在于任务本身。你是在使用executeOnExecutor() 运行它吗?
  • 我一开始也是这么想的。但是,日志条目“DL: EXECUTING”显示得非常快,这意味着 AsyncTask 实际上运行良好。事实上,LogCat 是 HttpResponse response = client.execute(request) 中 12 秒延迟的证据

标签: android html performance httpclient httpurlconnection


【解决方案1】:

代替

HttpClient client = new DefaultHttpClient();

尝试使用

HttpClient client = AndroidHttpClient.newInstance("MyApp/1.0");

【讨论】:

  • 我做了,但不幸的是没有明显的区别
猜你喜欢
  • 1970-01-01
  • 2016-09-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-11-26
  • 1970-01-01
  • 2017-11-24
相关资源
最近更新 更多