android httpclient hangs on second request to the server (connection timed out)

前端 未结 7 2131
后悔当初
后悔当初 2020-11-29 06:16

I\'m struggling with the following problem: My App makes sequence of requests to the http server using HttpClient. I use HttpPut for sending data to the server. First reques

7条回答
  •  野性不改
    2020-11-29 06:45

    I thought I would elaborate on the other answers. I experienced this problem also. The problem was because I was not consuming content.

    It seems if you don't then the connection will hold on to it and you are not able to send a new request with this same connection. For me it was a particularly difficult bug to spot as I was using the BasicResponseHandler provided in android. The code looks like this...

    public String handleResponse(final HttpResponse response)
                throws HttpResponseException, IOException {
            StatusLine statusLine = response.getStatusLine();
            if (statusLine.getStatusCode() >= 300) {
                throw new HttpResponseException(statusLine.getStatusCode(),
                        statusLine.getReasonPhrase());
            }
    
            HttpEntity entity = response.getEntity();
           return entity == null ? null : EntityUtils.toString(entity);
        }
    

    So if there is an status line above 300 then I don't consume the content. And there was content in my case. I made my own class like this...

    public class StringHandler implements ResponseHandler{
    
        @Override
        public BufferedInputStream handleResponse(HttpResponse response) throws IOException {
        public String handleResponse(final HttpResponse response)
                    throws HttpResponseException, IOException {
                StatusLine statusLine = response.getStatusLine();
               HttpEntity entity = response.getEntity();
                if (statusLine.getStatusCode() >= 300) {
                    if (entity != null) {
                        entity.consumeContent();
                    }
                    throw new HttpResponseException(statusLine.getStatusCode(),
                            statusLine.getReasonPhrase());
                }
    
    
               return entity == null ? null : EntityUtils.toString(entity);
            }
        }
    
    }
    

    So basically in any case consume the content!

提交回复
热议问题