2

我正在使用具有相同 URL 的基本 http 请求。有时它会返回一个长度为 -1 的实体。而响应状态为 OK 且实体不为空。

我运行该程序大约 10 次,它可以随机运行 2 次,而其他尝试因 "Content-type: text/html, lentgh: -1" 而失败。

还有什么我需要设置的吗?

HttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(textURL.toString());
HttpResponse response = client.execute(httpGet);
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
    HttpEntity entity = response.getEntity();
    System.out.println(entity.getContentType() + ", length: " + entity.getContentLength());
}
4

1 回答 1

1

我也遇到了同样的问题!我认为通过该方法获取的内容长度可能只是从标题中获取!但有时没有内容长度的标题;如果你真的想得到长度,你可以自己消费内容。然后你可以得到长度;

public String toString()
{
    InputStream instream=null;
    try{
        instream = this.getContent();
         Charset charset = null;
         if (instream == null) {
                return null;
         }
         int i = (int)this.getContentLength();
         if (i < 0) {
               i = 4096;
         }
         final ContentType contentType = ContentType.get(this);
         if (contentType != null) {
                charset = contentType.getCharset();
         }
         if (charset == null) {
                charset = HTTP.DEF_CONTENT_CHARSET;
         }
         final Reader reader = new InputStreamReader(instream, charset);
         final CharArrayBuffer buffer = new CharArrayBuffer(i);
         final char[] tmp = new char[1024];
         int l;
         int length=0;
         while((l = reader.read(tmp)) != -1) {
               buffer.append(tmp, 0, l);
               length+=l;
         }
         setContentLength(length*2);
         return buffer.toString();
    }
    catch(Exception e)
    {
        e.printStackTrace();
    }
    finally{
        try {
            instream.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    return "";
}
于 2015-09-04T09:08:04.763 回答