废话少说,直接上代码,以前都是调用别人写好的,现在有时间自己弄下,具体功能如下:
1、httpclient http 线程池:
2、httpclient https(单向不验证证书) 线程池:
https在%tomcat_home%/conf/server.xml里面的配置文件
maxthreads="150" scheme="https" secure="true"
clientauth="false" keystorefile="d:/tomcat.keystore"
keystorepass="heikaim" sslprotocol="tls" executor="tomcatthreadpool"/>
其中 clientauth="false"表示不开启证书验证,只是单存的走https
package com.abin.lee.util;
import org.apache.commons.collections4.maputils;
import org.apache.commons.lang3.stringutils;
import org.apache.http.*;
import org.apache.http.client.httprequestretryhandler;
import org.apache.http.client.config.cookiespecs;
import org.apache.http.client.config.requestconfig;
import org.apache.http.client.entity.urlencodedformentity;
import org.apache.http.client.methods.closeablehttpresponse;
import org.apache.http.client.methods.httpget;
import org.apache.http.client.methods.httppost;
import org.apache.http.client.protocol.httpclientcontext;
import org.apache.http.config.registry;
import org.apache.http.config.registrybuilder;
import org.apache.http.conn.connecttimeoutexception;
import org.apache.http.conn.socket.connectionsocketfactory;
import org.apache.http.conn.socket.plainconnectionsocketfactory;
import org.apache.http.conn.ssl.noophostnameverifier;
import org.apache.http.conn.ssl.sslconnectionsocketfactory;
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.basicheader;
import org.apache.http.message.basicnamevaluepair;
import org.apache.http.protocol.httpcontext;
import org.apache.http.util.entityutils;
import javax.net.ssl.*;
import java.io.ioexception;
import java.io.interruptedioexception;
import java.net.unknownhostexception;
import java.nio.charset.charset;
import java.security.cert.certificateexception;
import java.security.cert.x509certificate;
import java.util.*;
/**
* created with intellij idea.
* user: abin
* date: 16-4-18
* time: 上午10:24
* to change this template use file | settings | file templates.
*/
public class httpclientutil {
private static closeablehttpclient httpsclient = null;
private static closeablehttpclient httpclient = null;
static {
httpclient = gethttpclient();
httpsclient = gethttpsclient();
}
public static closeablehttpclient gethttpclient() {
try {
httpclient = httpclients.custom()
.setconnectionmanager(poolmanager.gethttppoolinstance())
.setconnectionmanagershared(true)
.setdefaultrequestconfig(requestconfig())
.setretryhandler(retryhandler())
.build();
} catch (exception e) {
e.printstacktrace();
}
return httpclient;
}
public static closeablehttpclient gethttpsclient() {
try {
//secure protocol implementation.
sslcontext ctx = sslcontext.getinstance("ssl");
//implementation of a trust manager for x509 certificates
trustmanager x509trustmanager = new x509trustmanager() {
public void checkclienttrusted(x509certificate[] xcs,
string string) throws certificateexception {
}
public void checkservertrusted(x509certificate[] xcs,
string string) throws certificateexception {
}
public x509certificate[] getacceptedissuers() {
return null;
}
};
ctx.init(null, new trustmanager[]{x509trustmanager}, null);
//首先设置全局的标准cookie策略
// requestconfig requestconfig = requestconfig.custom().setcookiespec(cookiespecs.standard_strict).build();
connectionsocketfactory connectionsocketfactory = new sslconnectionsocketfactory(ctx, hostnameverifier);
registry socketfactoryregistry = registrybuilder.create()
.register("http", plainconnectionsocketfactory.instance)
.register("https", connectionsocketfactory).build();
// 设置连接池
httpsclient = httpclients.custom()
.setconnectionmanager(poolsmanager.gethttpspoolinstance(socketfactoryregistry))
.setconnectionmanagershared(true)
.setdefaultrequestconfig(requestconfig())
.setretryhandler(retryhandler())
.build();
} catch (exception e) {
e.printstacktrace();
}
return httpsclient;
}
// 配置请求的超时设置
//首先设置全局的标准cookie策略
public static requestconfig requestconfig(){
requestconfig requestconfig = requestconfig.custom()
.setcookiespec(cookiespecs.standard_strict)
.setconnectionrequesttimeout(20000)
.setconnecttimeout(20000)
.setsockettimeout(20000)
.build();
return requestconfig;
}
public static httprequestretryhandler retryhandler(){
//请求重试处理
httprequestretryhandler httprequestretryhandler = new httprequestretryhandler() {
public boolean retryrequest(ioexception exception,int executioncount, httpcontext context) {
if (executioncount >= 5) {// 如果已经重试了5次,就放弃
return false;
}
if (exception instanceof nohttpresponseexception) {// 如果服务器丢掉了连接,那么就重试
return true;
}
if (exception instanceof sslhandshakeexception) {// 不要重试ssl握手异常
return false;
}
if (exception instanceof interruptedioexception) {// 超时
return false;
}
if (exception instanceof unknownhostexception) {// 目标服务器不可达
return false;
}
if (exception instanceof connecttimeoutexception) {// 连接被拒绝
return false;
}
if (exception instanceof sslexception) {// ssl握手异常
return false;
}
httpclientcontext clientcontext = httpclientcontext.adapt(context);
httprequest request = clientcontext.getrequest();
// 如果请求是幂等的,就再次尝试
if (!(request instanceof httpentityenclosingrequest)) {
return true;
}
return false;
}
};
return httprequestretryhandler;
}
//创建hostnameverifier
//用于解决javax.net.ssl.sslexception: hostname in certificate didn't match: <123.125.97.66> != <123.125.97.241>
static hostnameverifier hostnameverifier = new noophostnameverifier(){
@override
public boolean verify(string s, sslsession sslsession) {
return super.verify(s, sslsession);
}
};
public static class poolmanager {
public static poolinghttpclientconnectionmanager clientconnectionmanager = null;
private static int maxtotal = 200;
private static int defaultmaxperroute = 100;
private poolmanager(){
clientconnectionmanager.setmaxtotal(maxtotal);
clientconnectionmanager.setdefaultmaxperroute(defaultmaxperroute);
}
private static class poolmanagerholder{
public static poolmanager instance = new poolmanager();
}
public static poolmanager getinstance() {
if(null == clientconnectionmanager)
clientconnectionmanager = new poolinghttpclientconnectionmanager();
return poolmanagerholder.instance;
}
public static poolinghttpclientconnectionmanager gethttppoolinstance() {
poolmanager.getinstance();
// system.out.println("getavailable=" clientconnectionmanager.gettotalstats().getavailable());
// system.out.println("getleased=" clientconnectionmanager.gettotalstats().getleased());
// system.out.println("getmax=" clientconnectionmanager.gettotalstats().getmax());
// system.out.println("getpending=" clientconnectionmanager.gettotalstats().getpending());
return poolmanager.clientconnectionmanager;
}
}
public static class poolsmanager {
public static poolinghttpclientconnectionmanager clientconnectionmanager = null;
private static int maxtotal = 200;
private static int defaultmaxperroute = 100;
private poolsmanager(){
clientconnectionmanager.setmaxtotal(maxtotal);
clientconnectionmanager.setdefaultmaxperroute(defaultmaxperroute);
}
private static class poolsmanagerholder{
public static poolsmanager instance = new poolsmanager();
}
public static poolsmanager getinstance(registry socketfactoryregistry) {
if(null == clientconnectionmanager)
clientconnectionmanager = new poolinghttpclientconnectionmanager(socketfactoryregistry);
return poolsmanagerholder.instance;
}
public static poolinghttpclientconnectionmanager gethttpspoolinstance(registry socketfactoryregistry) {
poolsmanager.getinstance(socketfactoryregistry);
// system.out.println("getavailable=" clientconnectionmanager.gettotalstats().getavailable());
// system.out.println("getleased=" clientconnectionmanager.gettotalstats().getleased());
// system.out.println("getmax=" clientconnectionmanager.gettotalstats().getmax());
// system.out.println("getpending=" clientconnectionmanager.gettotalstats().getpending());
return poolsmanager.clientconnectionmanager;
}
}
public static string httppost(map request, string httpurl){
string result = "";
closeablehttpclient httpclient = gethttpclient();
try {
if(maputils.isempty(request))
throw new exception("请求参数不能为空");
httppost httppost = new httppost(httpurl);
list nvps = new arraylist();
for(iterator> iterator=request.entryset().iterator(); iterator.hasnext();){
map.entry entry = iterator.next();
nvps.add(new basicnamevaluepair(entry.getkey(), entry.getvalue()));
}
httppost.setentity(new urlencodedformentity(nvps, consts.utf_8));
system.out.println("executing request: " httppost.getrequestline());
closeablehttpresponse response = httpclient.execute(httppost);
result = entityutils.tostring(response.getentity());
system.out.println("executing response: " result);
} catch (exception e) {
throw new runtimeexception(e);
} finally {
try {
httpclient.close();
} catch (ioexception e) {
e.printstacktrace();
}
}
return result;
}
public static string httppost(string json, string httpurl, map headers){
string result = "";
closeablehttpclient httpclient = gethttpclient();
try {
if(stringutils.isblank(json))
throw new exception("请求参数不能为空");
httppost httppost = new httppost(httpurl);
for(iterator> iterator=headers.entryset().iterator();iterator.hasnext();){
map.entry entry = iterator.next();
header header = new basicheader(entry.getkey(), entry.getvalue());
httppost.setheader(header);
}
httppost.setentity(new stringentity(json, charset.forname("utf-8")));
system.out.println("executing request: " httppost.getrequestline());
closeablehttpresponse response = httpclient.execute(httppost);
result = entityutils.tostring(response.getentity());
system.out.println("executing response: " result);
} catch (exception e) {
throw new runtimeexception(e);
} finally {
try {
httpclient.close();
} catch (ioexception e) {
e.printstacktrace();
}
}
return result;
}
public static string httpget(string httpurl, map headers) {
string result = "";
closeablehttpclient httpclient = gethttpclient();
try {
httpget httpget = new httpget(httpurl);
system.out.println("executing request: " httpget.getrequestline());
for(iterator> iterator=headers.entryset().iterator();iterator.hasnext();){
map.entry entry = iterator.next();
header header = new basicheader(entry.getkey(), entry.getvalue());
httpget.setheader(header);
}
closeablehttpresponse response = httpclient.execute(httpget);
result = entityutils.tostring(response.getentity());
system.out.println("executing response: " result);
} catch (exception e) {
throw new runtimeexception(e);
} finally {
try {
httpclient.close();
} catch (ioexception e) {
e.printstacktrace();
}
}
return result;
}
public static string httpget(string httpurl) {
string result = "";
closeablehttpclient httpclient = gethttpclient();
try {
httpget httpget = new httpget(httpurl);
system.out.println("executing request: " httpget.getrequestline());
closeablehttpresponse response = httpclient.execute(httpget);
result = entityutils.tostring(response.getentity());
system.out.println("executing response: " result);
} catch (exception e) {
throw new runtimeexception(e);
} finally {
try {
httpclient.close();
} catch (ioexception e) {
e.printstacktrace();
}
}
return result;
}
maven依赖:
org.apache.httpcomponents
4.5.2
org.apache.httpcomponents
4.4.4
org.apache.httpcomponents
4.5.2
<dependency>
<groupid>org.apache.commonsgroupid>
<artifactid>commons-collections4artifactid>
<version>4.1version>
dependency>