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

来源:互联网 发布:剑三南风萝莉捏脸数据 编辑:程序博客网 时间:2024/05/21 01:32

转自百度经验

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() {// 信任所有@Overridepublic 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");// setHeaderpost.addHeader("Content-type","application/json");// setEntitypost.setEntity(paramEntity);// 执行请求并得到返回结果HttpClient client = HttpClientUtils.client;HttpResponse response = client.execute(post);HttpEntity entity = response.getEntity();



0 0