3

我正在编写一个 Java 程序,它使用 Apache-HttpComponents 加载页面并将其 HTML 打印到控制台;但是,该程序在抛出此错误之前仅打印部分 HTML:Exception in thread "main" java.net.SocketException: socket closed.每次运行程序时,异常之前显示的 HTML 部分完全相同,并且在 Google、Yahoo 和 Craigslist 的这个简化示例中出现错误:

String USERAGENT = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.22 (KHTML, like Gecko) Chrome/25.0.1364.172 Safari/537.22";
DefaultHttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet("http://www.craigslist.org");
get.setHeader(HTTP.USER_AGENT,USERAGENT);
HttpResponse page = client.execute(get);
get.releaseConnection();
InputStream stream = page.getEntity().getContent();
try{
    BufferedReader br = new BufferedReader(new InputStreamReader(stream));
    String line = "";
    while ((line = br.readLine()) != null){
        System.out.println(line);
    }
}
finally{
    EntityUtils.consume(page.getEntity());
}
4

1 回答 1

6

我发现get.releaseConnection();在我阅读完 HTML 之前不应该调用它。EntityUtils.consume(page.getEntity());修复上述代码后立即调用它。

于 2013-05-28T17:49:16.550 回答