首页 > Web开发 > 详细

httpclient: 设置连接池及超时配置,请求数据:PoolingHttpClientConnectionManager

时间:2019-06-26 22:54:06      阅读:1305      评论:0      收藏:0      [点我收藏+]

 

public static void main(String[] args) throws Exception{
		//httpclient连接池
		
		//创建连接池
		PoolingHttpClientConnectionManager cManager = new PoolingHttpClientConnectionManager();
		//设置最大连接数
		cManager.setMaxTotal(50);
		//设置每个主机地址的并发数
		cManager.setDefaultMaxPerRoute(20);
		
		//执行i请求
		doGet(cManager);
	}

	
	private static void doGet(PoolingHttpClientConnectionManager cm) throws Exception{
		//从连接池获取连接,每次不一样
		CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(cm).build();
		//设置http get
		HttpGet httpGet = new HttpGet("https://www.baidu.com");
		//设置请求参数
		RequestConfig config = RequestConfig.custom().setConnectTimeout(5000) //连接超时时间
				.setConnectionRequestTimeout(500) //从线程池中获取线程超时时间
				.setSocketTimeout(8000) //设置数据超时时间
				.setStaleConnectionCheckEnabled(true) //提交请求前检查连接是否可用
				.build();
		
		httpGet.setConfig(config);
		
		//返回数据
		CloseableHttpResponse response = null;
		
		try {
			response = httpClient.execute(httpGet);
			String con = EntityUtils.toString(response.getEntity(), "utf-8");
			System.out.println(con);
		}finally{
			if(response!=null){
				response.close();
			}
			httpClient.close();
		}
		
	}

  

httpclient: 设置连接池及超时配置,请求数据:PoolingHttpClientConnectionManager

原文:https://www.cnblogs.com/achengmu/p/11094329.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!