demo:
package test; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import org.apache.http.util.EntityUtils; import java.io.IOException; public class HttpClientPool { public static void main(String[] args) throws Exception { // 创建连接池管理器 PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(); // 设置最大连接数 cm.setMaxTotal(200); // 设置每个主机的并发数 cm.setDefaultMaxPerRoute(20); doGet(cm); doGet(cm); } private static void doGet(PoolingHttpClientConnectionManager cm) throws Exception { // 获取连接 CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(cm).build(); // 声明访问地址 HttpGet httpGet = new HttpGet("https://www.autohome.com.cn/bestauto/"); CloseableHttpResponse response = null; try { // 发起请求 response = httpClient.execute(httpGet); // 判断状态码是否是200 if (response.getStatusLine().getStatusCode() == 200) { // 解析数据 String content = EntityUtils.toString(response.getEntity(), "UTF-8"); System.out.println(content.length()); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { // 释放连接 if (response != null) { try { response.close(); } catch (IOException e) { e.printStackTrace(); } // 不能关闭HttpClient // httpClient.close(); } } } }
标签:http,请求,cm,参数,org,apache,import,response,HttpClient From: https://www.cnblogs.com/daitu66/p/17577637.html