https请求调用工具类,经过了SSL证书处理,本人亲测!
/**
* POST请求
*
* @param requestUrl
* @param objectData
* @param enableSSL
* @return
* @throws ClientProtocolException
* @throws IOException
*/
public static String POSTRequest(String requestUrl, Object objectData, Boolean enableSSL)
throws ClientProtocolException, IOException {
CloseableHttpClient client = createSSLClientDefault();
if (enableSSL) {
client = HttpClients.createDefault();
}
HttpPost httpPost = new HttpPost(requestUrl);
httpPost.setHeader("Content-Type", "application/json;charset=UTF-8");
String parameter = JSON.toJSONString(objectData);
StringEntity se = new StringEntity(parameter, "UTF-8");
se.setContentType("text/json");
httpPost.setEntity(se);
logger.info("请求AISP:" + parameter);
CloseableHttpResponse response = client.execute(httpPost);
HttpEntity entity = response.getEntity();
String result = EntityUtils.toString(entity, "UTF-8");
logger.info("AISP返回结果:" + result);
return result;
}
关键处理部分:
/**
* 处理绕过SSL证书校验
* @return
*/
private static CloseableHttpClient createSSLClientDefault() {
try {
X509TrustManager x509mgr = new X509TrustManager() {
@Override
public void checkClientTrusted(X509Certificate[] xcs, String string) throws CertificateException {
logger.info(string);
}
@Override
public void checkServerTrusted(X509Certificate[] xcs, String string) throws CertificateException {
logger.info(string);
}
@Override
public X509Certificate[] getAcceptedIssuers() {
return null;
}
};
SSLContext sslContext = SSLContext.getInstance("TLSv1.2");
sslContext.init(null, new TrustManager[] { x509mgr }, null);
//创建HttpsURLConnection对象,并设置其SSLSocketFactory对象
@SuppressWarnings("deprecation")
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext,
SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
return HttpClients.custom().setSSLSocketFactory(sslsf).build();
} catch (KeyManagementException e) {
logger.info(e.getMessage());
} catch (NoSuchAlgorithmException e) {
logger.info(e.getMessage());
} catch (Exception e) {
logger.info(e.getMessage());
}
return HttpClients.createDefault();
}