Apache HttpClient响应内容长度返回-1

时间:2013-09-10 19:03:31

标签: java http apache-httpcomponents

为什么以下代码返回-1?似乎请求失败。

public static void main(String[] args)
{
    DefaultHttpClient httpClient = new DefaultHttpClient();
    HttpGet httpGet = new HttpGet("http://www.google.de");

    HttpResponse response;
    try
    {
        response = httpClient.execute(httpGet);
        HttpEntity entity = response.getEntity();
        EntityUtils.consume(entity);

        // Prints -1
        System.out.println(entity.getContentLength());
    }
    catch (ClientProtocolException e)
    {
        e.printStackTrace();
    }
    catch (IOException e)
    {
        e.printStackTrace();
    }
    finally
    {
        httpGet.releaseConnection();
    }
}

是否可以将响应作为String?

3 个答案:

答案 0 :(得分:5)

尝试运行

Header[] headers = response.getAllHeaders();
for (Header header : headers) {
    System.out.println(header);
}

会打印

Date: Tue, 10 Sep 2013 19:10:04 GMT
Expires: -1
Cache-Control: private, max-age=0
Content-Type: text/html; charset=ISO-8859-1
Set-Cookie: PREF=ID=dad7e2356ddb3b7a:FF=0:TM=1378840204:LM=1378840204:S=vQcLzVPbOOTxfvL4; expires=Thu, 10-Sep-2015 19:10:04 GMT; path=/; domain=.google.de
Set-Cookie: NID=67=S11HcqAV454IGRGMRo-AJpxAPxClJeRs4DRkAJQ5vI3YBh4anN3qS0EVeiYX_4XDTGN-mY86xTBoJ3Ncca7eNSdtGjcaG31pbCOuqsZEQMWwKn-7-6Dnizx395snehdA; expires=Wed, 12-Mar-2014 19:10:04 GMT; path=/; domain=.google.de; HttpOnly
P3P: CP="This is not a P3P policy! See http://www.google.com/support/accounts/bin/answer.py?hl=en&answer=151657 for more info."
Server: gws
X-XSS-Protection: 1; mode=block
X-Frame-Options: SAMEORIGIN
Alternate-Protocol: 80:quic
Transfer-Encoding: chunked

这不是问题,您请求的页面在其响应中不提供Content-Length标头。因此,HttpEntity#getContentLength()会返回-1

EntityUtils有许多方法,其中一些返回String

答案 1 :(得分:3)

请注意响应标题名称Transfer-Encoding。它的值是分块的,这意味着数据是逐块传递的。 Transfer-Encoding:chunked和Content-Length不会同时结束。 有两个原因。

  1. 服务器不希望发送内容长度。
  2. 或者当服务器刷新大小比服务器缓冲区大的数据时,服务器不知道内容长度。
  3. 因此,当没有内容长度标题时,您可以在内容主体之前找到每个分块的大小。例如:

    HTTP/1.1 200 OK
    
    Server: Apache-Coyote/1.1
    
    Set-Cookie: JSESSIONID=8A7461DDA53B4C4DD0E89D73219CB5F8; Path=/
    
    Content-Type: text/html;charset=UTF-8
    
    Transfer-Encoding: chunked
    
    Date: Wed, 18 Mar 2015 07:10:05 GMT
    
    11
    
    helloworld!
    
    3
    
    123
    
    0
    

    上面的标题和内容告诉我们,有两个块数据。第一个块的大小为11.第二个块的大小为3.因此内容长度为14。

    的问候, 细瓷

答案 2 :(得分:1)

如果您真的想在不关心内容的情况下获取内容长度,可以这样做。

EntityUtils.toByteArray(httpResponse.getEntity())。长度

相关问题