HttpClient4.3.x请求https的解决方案

转自百度经验

http://jingyan.baidu.com/article/e52e3615a2b18f40c60c51d1.html


-------------------------------------------------------------------------

需要的jar包

jdk

httpclient-4.3*.jar

------------------------

import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

import javax.net.ssl.SSLContext;

import org.apache.http.client.HttpClient;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContextBuilder;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;

public class IgnoreSSLUtils {
	
	public static HttpClient client;
	
	static {
		client = createSSLClientDefault();
	}

	public static CloseableHttpClient createSSLClientDefault() {
		try {
			SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
				// 信任所有
				@Override
				public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
					return true;
				}
			}).build();
			SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext);
			return HttpClients.custom().setSSLSocketFactory(sslsf).build();
		} catch (KeyManagementException e) {
			e.printStackTrace();
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		} catch (KeyStoreException e) {
			e.printStackTrace();
		}
		return HttpClients.createDefault();
	}
}
使用方法

HttpPost post = new HttpPost("https://.....");
BasicHttpEntity paramEntity = new BasicHttpEntity();
paramEntity.setContent(new ByteArrayInputStream(json.getBytes("UTF-8")));
paramEntity.setContentLength(json.getBytes("UTF-8").length);
paramEntity.setContentType("application/json");
// setHeader
post.addHeader("Content-type","application/json");
// setEntity
post.setEntity(paramEntity);
// 执行请求并得到返回结果
HttpClient client = HttpClientUtils.client;
HttpResponse response = client.execute(post);
HttpEntity entity = response.getEntity();



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值