我正在尝试借助 Apache HttpClient 4.2 (Java) 获取一系列网页。问题是:系列中的一些HttpEntities内容为空,即:
is = new ByteArrayInputStream(EntityUtils.toByteArray(entity))
System.out.println(response.getStatusLine());
System.out.println(is.available());
显示 HTTP/1.1 200 OK 和 0。对于其他显示,例如 HTTP/1.1 200 OK 和 64344。如果我重新启动代码,该系列中的另一个 HttpEntities 可能为空。我做了一个递归,在同一个程序中运行网页,直到获得非零内容——经过一些调用,我得到了它……我在 Win'XP 下运行程序。
代码本身(没有递归):
public InputStream loadURL(String url) throws IOException {
PoolingClientConnectionManager connManager = new PoolingClientConnectionManager();
DefaultHttpClient httpclient = new DefaultHttpClient(connManager);
InputStream is = null;
try {
HttpGet httpget = new HttpGet(url);
HttpResponse response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
if (entity != null) {
try {
System.out.println("========================================");
is = new ByteArrayInputStream(EntityUtils.toByteArray(entity));
System.out.println(is.available());
System.out.println(response.getStatusLine());
System.out.println("========================================");
} catch (IOException ex) {
throw ex;
} catch (RuntimeException ex) {
httpget.abort();
throw ex;
}
}
} catch (ClientProtocolException ex) {
throw ex;
} finally {
httpclient.getConnectionManager().shutdown();
}
return is;
}
InputStream 在外部代码中关闭。