【问题标题】:Apache HttpClient return entity with length -1Apache HttpClient 返回长度为 -1 的实体
【发布时间】:2015-09-04 17:08:04
【问题描述】:

我正在使用具有相同 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());
}

【问题讨论】:

    标签: entity httpclient response


    【解决方案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 "";
    }
    

    【讨论】:

      猜你喜欢
      • 2013-09-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多