单向认证
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContexts;
import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.File;
import java.io.FileInputStream;
import java.security.KeyStore;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
public class Httpclient43x {
public void sendMessage() throws Exception {
CloseableHttpClient httpclient = null;
HttpGet httpget = null;
CloseableHttpResponse response = null;
try {
KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
FileInputStream instream = new FileInputStream(new File("d:\\tomcat.keystore"));
try {
trustStore.load(instream, "123456".toCharArray());
} catch (CertificateException e) {
e.printStackTrace();
} finally {
try {
instream.close();
} catch (Exception ignore) {
}
}
SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial(trustStore, new TrustSelfSignedStrategy()).build();
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, new String[]{"TLSv1"}, null,
SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
httpget = new HttpGet("https://localhost:8080/test");
response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
System.out.println("----------------------------------------");
System.out.println(response.getStatusLine());
if (entity != null) {
System.out.println("Response content length: " + entity.getContentLength());
System.out.println(EntityUtils.toString(entity));
EntityUtils.consume(entity);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (response != null) {
response.close();
}
if (httpget != null) {
httpget.releaseConnection();
}
if (httpclient != null) {
httpclient.close();
}
}
}
忽略证书
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContexts;
import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.File;
import java.io.FileInputStream;
import java.security.KeyStore;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
public class Httpclient43x {
public void sendMessage() throws Exception {
CloseableHttpClient httpclient = null;
HttpGet httpget = null;
CloseableHttpResponse response = null;
try {
SSLConnectionSocketFactory sslsf2 = new SSLConnectionSocketFactory(ignoreSSL(),
SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
httpclient = HttpClients.custom().setSSLSocketFactory(sslsf2).build();
httpget = new HttpGet("https://localhost:8080/test");
response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
System.out.println("----------------------------------------");
System.out.println(response.getStatusLine());
if (entity != null) {
System.out.println("Response content length: " + entity.getContentLength());
System.out.println(EntityUtils.toString(entity));
EntityUtils.consume(entity);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (response != null) {
response.close();
}
if (httpget != null) {
httpget.releaseConnection();
}
if (httpclient != null) {
httpclient.close();
}
}
}
private static SSLContext ignoreSSL() {
try {
SSLContext sslContext = SSLContext.getInstance("SSLv3");
sslContext.init(null, new TrustManager[]{truseAllManager}, null);
return sslContext;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static TrustManager truseAllManager = new X509TrustManager() {
public X509Certificate[] getAcceptedIssuers() {
return null;
}
public void checkServerTrusted(X509Certificate[] arg0, String arg1)
throws CertificateException {
}
public void checkClientTrusted(X509Certificate[] arg0, String arg1)
throws CertificateException {
}
};
}
双向认证
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContexts;
import org.apache.http.util.EntityUtils;
import javax.net.ssl.SSLContext;
import java.io.File;
import java.io.FileInputStream;
import java.security.KeyStore;
public class HttpTwoWay2 {
public static void main(String[] args) throws Exception {
KeyStore keyStore = KeyStore.getInstance("PKCS12");
keyStore.load(new FileInputStream(new File("C:\\Users\\Administrator\\Desktop\\jiaoyiping.p12")), "123456".toCharArray());
SSLContext sslcontext = SSLContexts.custom()
.loadTrustMaterial(new File("D:\\truststore.jks"), "123456".toCharArray(), new TrustSelfSignedStrategy())
.loadKeyMaterial(keyStore, "cmcc".toCharArray())
.build();
SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(
sslcontext,
new String[]{"TLSv1"},
null,
SSLConnectionSocketFactory.getDefaultHostnameVerifier());
CloseableHttpClient httpclient = null;
HttpGet httpget = null;
CloseableHttpResponse response = null;
try {
httpclient = HttpClients.custom().setSSLSocketFactory(sslConnectionSocketFactory).build();
httpget = new HttpGet("https://10.2.5.116/PnsReceiver/ReceiveMessage");
System.out.println("Executing request " + httpget.getRequestLine());
response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
System.out.println(response.getStatusLine());
System.out.println(entity.getContent());
EntityUtils.consume(entity);
} finally {
if (response != null) {
response.close();
}
if (httpget != null) {
httpget.releaseConnection();
}
if (httpclient != null) {
httpclient.close();
}
}
}
}
连接池
写法一:
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContexts;
import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
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 javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.File;
import java.io.FileInputStream;
import java.security.KeyStore;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
public class Httpclient43x {
static CloseableHttpClient httpclient;
private static CloseableHttpClient getHttpclient(){
if(httpclient != null) {
return httpclient;
} else {
synchronized (Httpclient43x.class){
if(httpclient !=null) {
return httpclient;
} else {
SSLConnectionSocketFactory sslsf2 = new SSLConnectionSocketFactory(ignoreSSL(),
SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
.register("http", new PlainConnectionSocketFactory())
.register("https", sslsf2)
.build();
PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(registry);
cm.setMaxTotal(1000);
cm.setDefaultMaxPerRoute(200);
httpclient = HttpClients.custom().setConnectionManager(cm).build();
return httpclient;
}
}
}
}
public static void sendMessage() throws Exception {
HttpGet httpget = null;
CloseableHttpResponse response = null;
try {
httpget = new HttpGet("https://localhost:8443/myDemo/Ajax/serivceJ.action");
response = getHttpclient().execute(httpget);
HttpEntity entity = response.getEntity();
System.out.println("----------------------------------------");
System.out.println(response.getStatusLine());
if (entity != null) {
System.out.println("Response content length: " + entity.getContentLength());
System.out.println(EntityUtils.toString(entity));
EntityUtils.consume(entity);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (response != null) {
response.close();
}
if (httpget != null) {
httpget.releaseConnection();
}
}
}
private static SSLContext ignoreSSL() {
try {
SSLContext sslContext = SSLContext.getInstance("SSLv3");
sslContext.init(null, new TrustManager[]{truseAllManager}, null);
return sslContext;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static TrustManager truseAllManager = new X509TrustManager() {
public X509Certificate[] getAcceptedIssuers() {
return null;
}
public void checkServerTrusted(X509Certificate[] arg0, String arg1)
throws CertificateException {
}
public void checkClientTrusted(X509Certificate[] arg0, String arg1)
throws CertificateException {
}
};
}
写法二:
import com.google.common.base.Optional;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HeaderElement;
import org.apache.http.HeaderElementIterator;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
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.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.ConnectionKeepAliveStrategy;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.LayeredConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
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.HttpClientBuilder;
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 org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
public class HttpClient4Util {
private final static Logger logger = LoggerFactory
.getLogger(HttpClient4Util.class);
private CloseableHttpClient httpclient;
private RequestConfig requestConfig;
private PoolingHttpClientConnectionManager connManager;
private static HttpClient4Util httpClient4UtilNew;
private volatile boolean shutdown;
public synchronized static HttpClient4Util getInstance() throws Exception {
if (httpClient4UtilNew == null) {
httpClient4UtilNew = new HttpClient4Util();
httpClient4UtilNew.init();
}
return httpClient4UtilNew;
}
private HttpClient4Util() {
}
public void init() throws NoSuchAlgorithmException, KeyManagementException {
SSLContext sslCtx = SSLContext.getInstance("TLS");
X509TrustManager trustManager = new X509TrustManager() {
public X509Certificate[] getAcceptedIssuers() {
return null;
}
public void checkClientTrusted(X509Certificate[] arg0, String arg1)
throws CertificateException {
}
public void checkServerTrusted(X509Certificate[] arg0, String arg1)
throws CertificateException {
}
};
sslCtx.init(null, new TrustManager[]{trustManager}, null);
LayeredConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(
sslCtx, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
RegistryBuilder<ConnectionSocketFactory> registryBuilder = RegistryBuilder
.<ConnectionSocketFactory>create();
ConnectionSocketFactory plainSocketFactory = new PlainConnectionSocketFactory();
registryBuilder.register("http", plainSocketFactory);
registryBuilder.register("https", sslSocketFactory);
Registry<ConnectionSocketFactory> registry = registryBuilder.build();
connManager = new PoolingHttpClientConnectionManager(registry);
connManager.setMaxTotal(200);
connManager.setDefaultMaxPerRoute(20);
ConnectionKeepAliveStrategy myStrategy = new ConnectionKeepAliveStrategy() {
@Override
public long getKeepAliveDuration(HttpResponse response,
HttpContext context) {
HeaderElementIterator it = new BasicHeaderElementIterator(
response.headerIterator(HTTP.CONN_KEEP_ALIVE));
while (it.hasNext()) {
HeaderElement he = it.nextElement();
String param = he.getName();
String value = he.getValue();
if (null != value && "timeout".equalsIgnoreCase(param)) {
try {
return Long.parseLong(value) * 1000;
} catch (NumberFormatException ignore) {
}
}
}
return 20 * 1000;
}
};
httpclient = HttpClientBuilder.create().setConnectionManager(
connManager).setKeepAliveStrategy(myStrategy).build();
shutdown = false;
new Thread(new Runnable() {
@Override
public void run() {
while (!shutdown) {
try {
synchronized (this) {
wait(500);
connManager.closeExpiredConnections();
connManager.closeIdleConnections(40, TimeUnit.SECONDS);
}
} catch (Exception e) {
logger.error(e.getLocalizedMessage(), e);
}
}
}
}).start();
}
public byte[] doGet(String url, List<NameValuePair> nameValuePairs) {
CloseableHttpResponse response = null;
HttpGet httpget = new HttpGet();
try {
URIBuilder builder = new URIBuilder(url);
if (nameValuePairs != null && !nameValuePairs.isEmpty()) {
builder.setParameters(nameValuePairs);
}
httpget.setURI(builder.build());
httpget.setConfig(requestConfig);
response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
if (entity != null) {
return EntityUtils.toByteArray(entity);
}
} catch (Exception e) {
logger.error("http 请求异常", e);
} finally {
if (response != null) {
try {
response.close();
} catch (IOException e) {
logger.error("释放连接异常", e);
}
}
}
return null;
}
public byte[] doPost(String url, Map<String, String> heard, List<NameValuePair> queryParams, List<NameValuePair> formParams, String content,String charset, int timeout) {
if (StringUtils.isBlank(url)) {
return null;
}
CloseableHttpResponse response = null;
HttpPost httppost = new HttpPost();
try {
URIBuilder builder = new URIBuilder(url);
if (CollectionUtils.isNotEmpty(queryParams)) {
builder.setParameters(queryParams);
}
httppost.setURI(builder.build());
timeout = Optional.fromNullable(timeout).or(60000);
requestConfig = RequestConfig.custom()
.setConnectTimeout(timeout).setSocketTimeout(
timeout).build();
httppost.setConfig(requestConfig);
if (null != heard) {
for (String key : heard.keySet()) {
httppost.setHeader(key, heard.get(key));
}
}
if (CollectionUtils.isNotEmpty(formParams)) {
httppost.setEntity(new UrlEncodedFormEntity(formParams, charset));
}
if (StringUtils.isNotBlank(content)) {
httppost.setEntity(new StringEntity(content, charset));
}
response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
int stateCode = response.getStatusLine().getStatusCode();
if (HttpStatus.SC_OK != stateCode) {
logger.error("非正常响应[" + stateCode + "]", new String(EntityUtils.toByteArray(entity), charset));
return null;
}
if (entity != null) {
return EntityUtils.toByteArray(entity);
}
} catch (Exception e) {
logger.error("http请求异常", e);
} finally {
httppost.releaseConnection();
if (response != null) {
try {
response.close();
} catch (IOException e) {
logger.error("释放连接异常", e);
}
}
}
return null;
}
}