我正在编写一个 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());
}