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();



展开阅读全文

没有更多推荐了,返回首页