【问题标题】:Async task long delay on reading getEntity()读取 getEntity() 的异步任务长时间延迟
【发布时间】:2014-10-22 13:57:32
【问题描述】:

我正在从 REST 服务器读取数据。有时我会遇到很长的延迟,但在沟通之后:

protected JSONObject doInBackground(String... params)
...
HttpResponse response;
client = new DefaultHttpClient(); 
... 
HttpPost post = new HttpPost(sendURL);
StringEntity se = new StringEntity( postJSON.toString(), "UTF-8");  
Log.d(getClass().getName(), String.format("post object: %s", postJSON.toString()));
se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
post.setEntity(se);
response = client.execute(post);
Log.d(getClass().getName(), "Response received");

        if(response!=null){
            String responseStr = null;
            if (response.getStatusLine().getStatusCode() == 200){
                try {
                    Log.d(getClass().getName(), "Response status OK");
                    responseStr = EntityUtils.toString(response.getEntity());
                    Log.d(getClass().getName(), "Response String read: " 
...

在随机的时间间隔内,任务需要很长时间才能完成,从而造成无法接受的用户体验。日志中的时间戳表明对 response.getEntity() 的调用需要很长时间,30 秒甚至更多。诸如this 之类的问题表明对 getEntity() 的调用实际上确实涉及网络通信。是这样吗?还是因为 AsyncTask 没有获取资源而发生延迟?

【问题讨论】:

  • 您的实体有多大?你的服务器有多快?
  • 延迟不是响应大小的函数。由于我使用的是单个服务器,因此它的响应性本身不是问题。假设 getEntity 仍然是通信过程的一部分,它在任何给定时间的工作量都可能是一个问题。这确实是个问题。
  • 是的,getEntity() 仍然是通信过程的一部分。

标签: android android-asynctask


【解决方案1】:

是的,response.getEntity() 仍然是您的 HTTP 响应/通信的一部分。它只会返回一个HttpEntity,它包含您的响应。 EntityUtils.toString 是导致您无法接受的延迟的原因,因为它会阻止调用,直到它完成读取整个响应流并转换为字符串。延迟可能是由于网络连接/带宽缓慢,或者您的服务器响应缓慢。这种网络延迟有时在移动设备上是不可避免的,您需要显示一些 UI 更新/进度。

使用response.getEntity().getContent() 代替EntityUtils.toString 来获取底层inputStream 并在while 循环中手动读取它,定期调用onProgressUpdate 以便您的UI 可以显示某种进度。在完成inputStream 调用close() 之后,这将表明您的请求通信结束。见this SO question for a code snippet of while loop,别忘了拨打reader.close()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-20
    相关资源
    最近更新 更多