【工具笔记】java http线程池请求 httpclient

<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.5.12</version>
</dependency>
import java.util.List;
import java.util.Map;

import org.apache.http.HeaderElement;
import org.apache.http.HeaderElementIterator;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.*;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.conn.ConnectionKeepAliveStrategy;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
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.message.BasicHeaderElementIterator;
import org.apache.http.protocol.HTTP;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.EntityUtils;

import com.alibaba.fastjson.JSONObject;

/**
 * http访问线程池工具
 * @author 孔小胖子
 */
public class HttpClientPoolUtil {
	public static PoolingHttpClientConnectionManager cm = null;
	public static CloseableHttpClient httpClient = null;
	private static final String DEFAULT_CONTENT_TYPE = "application/x-www-form-urlencoded";
	private static final String DEFAULT_CHATSET = "UTF-8";
	private static final int DEFAUL_TTIME_OUT = 3;
	private static final int count = 60;
	private static final int totalCount = 300;
	private static final int HTTP_DEFAULT_KEEP_TIME =15;

	/**
	 * 
	 * @DESCRIPTION:初始化连接池
	 */
	public static synchronized void initPools() {
		if (httpClient == null) {
			cm = new PoolingHttpClientConnectionManager();
			cm.setDefaultMaxPerRoute(count);
			cm.setMaxTotal(totalCount);
			httpClient = HttpClients.custom().setKeepAliveStrategy(connectionKeepAliveStrategy).setConnectionManager(cm).build();
		}
	}

	public static CloseableHttpClient getHttpClient() {
		return httpClient;
	}

	public static PoolingHttpClientConnectionManager getHttpConnectionManager() {
		return cm;
	}

	public static String executePost(String uri, List<NameValuePair> nvps, String contentType, Map<String, String> headers) {
		HttpEntity httpEntity = null;
		HttpEntityEnclosingRequestBase method = null;
		String responseBody = "";
		try {
			if (httpClient == null) {
				initPools();
			}
			method = (HttpEntityEnclosingRequestBase) getRequest(uri, HttpPost.METHOD_NAME, contentType==null?DEFAULT_CONTENT_TYPE:contentType, 0, headers);
			StringEntity stringEntity = null;
			if (ContentType.APPLICATION_JSON.getMimeType().contains(contentType)) {
				JSONObject paramMap = new JSONObject();
				if(nvps!=null && nvps.size()>0) {
					for(NameValuePair nvp : nvps) {
						paramMap.put(nvp.getName(), nvp.getValue());
					}
				}
				stringEntity = new StringEntity((nvps != null && nvps.size() != 0) ? paramMap.toJSONString() : "", ContentType.APPLICATION_JSON);
			} else {
				stringEntity = new UrlEncodedFormEntity(nvps, DEFAULT_CHATSET);
			}
			stringEntity.setContentEncoding(DEFAULT_CHATSET);
		   	stringEntity.setContentType(contentType==null?DEFAULT_CONTENT_TYPE:contentType);
			method.setEntity(stringEntity);
			HttpContext context = HttpClientContext.create();
			CloseableHttpResponse httpResponse = httpClient.execute(method, context);
			httpEntity = httpResponse.getEntity();
			if (httpEntity != null) {
				responseBody = EntityUtils.toString(httpEntity, DEFAULT_CHATSET);
			}
		} catch (Exception e) {
			if (method != null) {
				method.abort();
			}
		} finally {
			if (httpEntity != null) {
				try {
					EntityUtils.consumeQuietly(httpEntity);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
		return responseBody;
	}

	public static String executeGet(String uri, String contentType, Map<String, String> headers) {
		HttpEntity httpEntity = null;
		HttpRequestBase method = null;
		String responseBody = "";
		try {
			if (httpClient == null) {
				initPools();
			}
			method = getRequest(uri, HttpGet.METHOD_NAME,  contentType==null?DEFAULT_CONTENT_TYPE:contentType, 0, headers);
			HttpContext context = HttpClientContext.create();
			CloseableHttpResponse httpResponse = httpClient.execute(method, context);
			httpEntity = httpResponse.getEntity();
			if (httpEntity != null) {
				responseBody = EntityUtils.toString(httpEntity, DEFAULT_CHATSET);
			}
		} catch (Exception e) {
			if (method != null) {
				method.abort();
			}
			e.printStackTrace();
		} finally {
			if (httpEntity != null) {
				try {
					EntityUtils.consumeQuietly(httpEntity);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
		return responseBody;
	}
	
	private static ConnectionKeepAliveStrategy connectionKeepAliveStrategy = new ConnectionKeepAliveStrategy() {
		public long getKeepAliveDuration(HttpResponse response, HttpContext context) {
			HeaderElementIterator it = new BasicHeaderElementIterator(response.headerIterator(HTTP.CONN_KEEP_ALIVE));
			int keepTime = HTTP_DEFAULT_KEEP_TIME;
			while (it.hasNext()) {
				HeaderElement he = it.nextElement();
				String param = he.getName();
				String value = he.getValue();
				if (value != null && param.equalsIgnoreCase("timeout")) {
					try {
						return Long.parseLong(value) * 1000;
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}
			return keepTime * 1000L;
		}
	};
	
	private static HttpRequestBase getRequest(String uri, String methodName, String contentType, int timeout, Map<String, String> headers) {
		if (httpClient == null) {
			initPools();
		}
		HttpRequestBase method = null;
		if (timeout <= 0) {
			timeout = DEFAUL_TTIME_OUT;
		}
		RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(timeout * 1000)
				.setConnectTimeout(timeout * 1000).setConnectionRequestTimeout(timeout * 1000)
				.setExpectContinueEnabled(false).build();
		if (HttpPut.METHOD_NAME.equalsIgnoreCase(methodName)) {
			method = new HttpPut(uri);
		} else if (HttpPost.METHOD_NAME.equalsIgnoreCase(methodName)) {
			method = new HttpPost(uri);
		} else if (HttpGet.METHOD_NAME.equalsIgnoreCase(methodName)) {
			method = new HttpGet(uri);
		} else {
			method = new HttpPost(uri);
		}
		if (contentType==null||"".equals(contentType)) {
			contentType = DEFAULT_CONTENT_TYPE;
		}
		if (headers!=null && headers.keySet().size() > 0) {
			for (String key : headers.keySet()) {
				method.addHeader(key, headers.get(key));
			}
		}
		method.addHeader("Content-Type", contentType);
		method.addHeader("Accept", contentType);
		method.setConfig(requestConfig);
		return method;
	}
}

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

孔小胖子

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值