最近在做一个项目,使用的是api接口,需要使用httpClient调用第三方的接口 特意整理了一下代码 封装了httpclientUtil 方便使用
首先封装各种不同的请求方式
public class HttpClientUtil {
private final static Logger logger = LoggerFactory.getLogger(HttpClientUtil.class.getSimpleName());
// 连接超时
private static final int connection_timeout = 1000 * 60 * 2;
// 指定时间内服务器端没有反应
private static final int socket_timeout = 1000 * 40;
// 请求超时
private static final int request_timeout = 1000 * 40;
// 每个主机
private static int max_host_connections = 2000;
// 总的连接数
private static int max_total_connections = 5000;
private static final String charset = "utf-8";
// 自定义头前缀
private static final String filter_header_prefix = "httpclient_";
// 请求格式,默认json格式
private static final String request_format = "httpclient_format";
private static HttpClient httpClient = null;
private static Set<String> excludeHeaders = new HashSet<String>();
private static RequestConfig default_request_config = null;
static {
default_request_config = RequestConfig.custom().setSocketTimeout(socket_timeout).setConnectTimeout(
connection_timeout).setConnectionRequestTimeout(request_timeout).build();
PoolingHttpClientConnectionManager connMgr = new PoolingHttpClientConnectionManager();
connMgr.setMaxTotal(max_total_connections);
connMgr.setDefaultMaxPerRoute(max_host_connections);
HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
httpClientBuilder.setConnectionManager(connMgr);
httpClientBuilder.setDefaultRequestConfig(default_request_config);
ConnectionConfig connConfig = ConnectionConfig.custom().setCharset(Charset.forName(charset)).build();
httpClientBuilder.setDefaultConnectionConfig(connConfig);
httpClient = httpClientBuilder.build();
//过滤头
excludeHeaders.add(HTTP.CONTENT_LEN.toLowerCase());