0

I am reading data from a REST server. on occasion I am getting very long delays, but after the communication:

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: " 
...

At random intervals the task takes a very long time to complete, creating an unacceptable user experience. The timestamps in the log indicate that the call to response.getEntity() is taking a very long time, 30 seconds and more. Questions such as this indicate that the call to getEntity() does in fact involve network communication. Is this the case? Or is the delay happening because the AsyncTask is not getting resources?

Community
  • 1
  • 1
Aharon Manne
  • 712
  • 3
  • 11
  • 34
  • How large is your entity? How quick is your server? – 323go Oct 22 '14 at 13:59
  • The delay is not a function of response size. Since I am working with a single server, its responsiveness as such is not the issue. Its workload at any given time might be an issue, assuming that getEntity is still part of the communication process. That is really the question. – Aharon Manne Oct 22 '14 at 14:06
  • Yes, `getEntity()` is still part of the communication process. – 323go Oct 22 '14 at 14:10

1 Answers1

0

yes, response.getEntity() is still part of your HTTP response/communication. It will just return an HttpEntity, which wraps your response. EntityUtils.toString is the one thats causing your unacceptable delay, as it blocks the call until its done reading entire response stream and convert into string. The delay can be due to slow network connection/bandwidth, or your server slow response. These kind of network delays are sometimes unavoidable on mobile devices, you will need to show some UI update/progress.

Instead of EntityUtils.toString, use response.getEntity().getContent() to get the underlying inputStream and manually read it in a while loop, periodically calling onProgressUpdate so your UI can show some kind of progress. After done with the inputStream call close() , which will indicate the end of your request communication. See this SO question for a code snippet of while loop, dont forget to call reader.close()

Community
  • 1
  • 1
ashoke
  • 6,441
  • 2
  • 26
  • 25