创建连接池,从连接池里获取HttpClient对象
public class HttpClientPoolTest {
public static void main(String[] args) {
//1.创建连接池管理器
PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
//连接数和主机最大连接数可以理解为:一共分配100个连接 主机爬取不同的网站的时候 每一个网站只能爬取10次
//设置连接数
cm.setMaxTotal(100);
//设置每个主机最大连接数
cm.setDefaultMaxPerRoute(10);
//2.使用连接池管理器发起请求
doGet(cm);
doGet(cm);
}
private static void doGet(PoolingHttpClientConnectionManager cm) {
//不是每次创建新的HttpClient 而是从连接池中获取HttpClient对象
CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(cm).build();
HttpGet httpGet = new HttpGet("https://www.ziroom.com/z/r1/?isOpen=0");
CloseableHttpResponse response = null;
try {
response = httpClient.execute(httpGet);
if(response.getStatusLine().getStatusCode()==200){
String content = EntityUtils.toString(response.getEntity(),"utf8");
System.out.println(content.length());
}
} catch (IOException e) {
e.printStackTrace();
}finally {
if(response != null){
try {
response.close();
} catch (IOException e) {
e.printStackTrace();
}
//不能关闭httpClient,由连接池管理httpClient
//httpClient.close();
}
}
}
}