private static CloseableHttpClient createSSLClientDefault() {
try {
//调用SSL之前取消重写验证方法,取消检测SSL
X509TrustManager trustManager =new X509TrustManager() {
//检查客户端证书
@Override
public void checkClientTrusted(X509Certificate[] x509Certificates, String s) {
}
//检查服务器证书
@Override
public void checkServerTrusted(X509Certificate[] x509Certificates, String s) {
}
//返回受信任的X509证书数组
@Override
public X509Certificate[] getAcceptedIssuers() {
return null;
}
};
//设置TLS-->数据通信之间保证数据的保密性和完整性
SSLContext ctx = SSLContext.getInstance(SSLConnectionSocketFactory.TLS);
//初始化
ctx.init(null, new TrustManager[]{trustManager}, null);
SSLConnectionSocketFactory socketFactory =new SSLConnectionSocketFactory(ctx, NoopHostnameVerifier.INSTANCE);
RequestConfig requestConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD_STRICT).setExpectContinueEnabled(Boolean.TRUE).setTargetPreferredAuthSchemes(Arrays.asList(AuthSchemes.NTLM, AuthSchemes.DIGEST)).setProxyPreferredAuthSchemes(Arrays.asList(AuthSchemes.BASIC)).build();
//创建Registry
Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
.register("http", PlainConnectionSocketFactory.INSTANCE).register("https", socketFactory).build();
//创建ConnectionManager,添加Connection配置信息
PoolingHttpClientConnectionManager connectionManager =new PoolingHttpClientConnectionManager(socketFactoryRegistry);
CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(connectionManager).setDefaultRequestConfig(requestConfig).build();
return httpClient;
} catch (NoSuchAlgorithmException e) {
new RuntimeException(e);
} catch (KeyManagementException e) {
new RuntimeException(e);
}
return HttpClients.createDefault();
}
//Post
public static void httpDoPost(String url, JSONObject params) {
//创建Client实例
CloseableHttpClient client =createSSLClientDefault();
// 创建httppost实例
HttpPost httpPost =new HttpPost(url);
//添加请求头
httpPost.addHeader("Content-Type", "application/json;charset=utf-8");
try {
httpPost.setEntity(new StringEntity(params.toJSONString(), "utf-8"));
CloseableHttpResponse resp = client.execute(httpPost);
try {
// 获取响应entity
HttpEntity respEntity = resp.getEntity();
String result = EntityUtils.toString(respEntity, "UTF-8");
} finally {
resp.close();
}
} catch (ClientProtocolException e) {
new RuntimeException(e);
} catch (UnsupportedEncodingException e) {
new RuntimeException(e);
} catch (IOException e) {
new RuntimeException(e);
} finally {
try {
client.close();
} catch (Exception e) {
Logger.getLogger(HttpsClientUtil.class.getName()).log(Level.SEVERE, null, e);
}
}
}
Get:
public static void httpDoGet(String url, Map<String, Object> params) {
CloseableHttpClient client =createSSLClientDefault();
String apiUrl = url;
StringBuffer sb =new StringBuffer();
int i =0;
for (String key : params.keySet()) {
if (i ==0) {
sb.append("?");
} else {
sb.append("&");
}
sb.append(key).append("=").append(params.get(key));
i++;
}
apiUrl += sb;
//创建get请求
HttpGet httpGet =new HttpGet(apiUrl);
//添加请求头
httpGet.addHeader("Content-Type", "application/json;charset=utf-8");
try {
CloseableHttpResponse response = client.execute(httpGet);
try {
HttpEntity entity = response.getEntity();
String result = EntityUtils.toString(entity, "UTF-8");
} catch (Exception e) {
response.close();
}
} catch (IOException e) {
new RuntimeException(e);
} finally {
try {
client.close();
} catch (Exception e) {
Logger.getLogger(HttpsClientUtil.class.getName()).log(Level.SEVERE, null, e);
}
}
}