NutzCN Logo
问答 HttpClient 抓取网页
发布于 3094天前 作者 threefish 4718 次浏览 复制 上一个帖子 下一个帖子
标签: http

HttpClient

org.apache.http.ConnectionClosedException: Premature end of Content-Length delimited message body (expected: 9353; received: 1179)

这种问题应该如何处理呢?
网页长度是9353 但是只收到了1179

6 回复

自己的网站?

这里是HttpClient请求

.............
 HttpEntity entity = response.getEntity();
  InputStream inputStream = entity.getContent();                                

这里是处理成字符串

public static String streamAsString(InputStream inputStream, String encoding) {
        String tempstr = "";
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        byte[] bytes = new byte[1024];
        int len = 0;
        try {
            while ((len = inputStream.read(bytes)) != -1) {
                byteArrayOutputStream.write(bytes, 0, len);
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        try {
            if (encoding == null || "".equals(encoding)) {
                tempstr = new String(byteArrayOutputStream.toByteArray());
            } else {
                bytes = byteArrayOutputStream.toByteArray();
                tempstr = new String(bytes, encoding);
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return tempstr;
    }

@wendal 不是自己的网站,抓取别人的

对方网站应该是分段返回数据。这是Response Headers
Accept-Ranges:bytes
Content-Length:9353
Content-Type:text/html
Date:Tue, 27 Oct 2015 07:49:08 GMT
ETag:"68d06417c1fed01:9de"
Last-Modified:Sun, 04 Oct 2015 16:24:06 GMT
Server:Microsoft-IIS/6.0
X-Powered-By:ASP.NET

好复杂的代码,用nutz的话一行搞定

return Http.get("https://nutz.cn");

不过,如果不是你自己的网站,而浏览器访问正常的话,就需要考虑是不是被封了

@wendal 确实和网络有很大关系,使用本地网络没有问题。程序使用国外代理后就出现问题了,翻墙后浏览器还是可以正常访问的。

添加回复
请先登陆
回到顶部