- 跳过证书校验
/**
* 跳过证书验证
*
* @return
*/
public static CloseableHttpClient createOverSSLClientDefault() {
try {
SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
// 信任所有
public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
return true;
}
}).build();
HostnameVerifier hostnameVerifier = NoopHostnameVerifier.INSTANCE;
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, hostnameVerifier);
return HttpClients.custom().setSSLSocketFactory(sslsf).build();
} catch (KeyManagementException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (KeyStoreException e) {
e.printStackTrace();
}
return HttpClients.createDefault();
}
- 携带证书访问
private static CloseableHttpClient createSSLClientDefault() throws Exception {
CertificateFactory cAf = CertificateFactory.getInstance("X.509");
String path = HuaweiApplication.class.getProtectionDomain().getCodeSource().getLocation().getPath();
//windows下使用
// FileInputStream caIn = new FileInputStream("D://vhr.cer");
// X509Certificate ca = (X509Certificate) cAf.generateCertificate(caIn);
//linux下使用
InputStream resourceAsStream = HuaweiApplication.class.getResourceAsStream("/vhr.cer");
X509Certificate ca = (X509Certificate) cAf.generateCertificate(resourceAsStream);
KeyStore caKs = KeyStore.getInstance("JKS");
caKs.load(null, null);
caKs.setCertificateEntry("ca-certificate", ca);
TrustManagerFactory tmf = TrustManagerFactory.getInstance("PKIX");
tmf.init(caKs);
// finally, create SSL socket factory
SSLContext context = SSLContext.getInstance("TLSv1.2");
context.init(null, tmf.getTrustManagers(), new SecureRandom());
SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(context);
// Create custom httpClient 创建自定义httpClient连接
CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(sslConnectionSocketFactory)
.disableAutomaticRetries()
.setRedirectStrategy(new LaxRedirectStrategy()).build();
return httpClient;
}
3.证书文件位置
4.访问方法,以HttpPost为例
try
{
HttpPost method = new HttpPost("https://地址");
method.setHeader("Content-type", "application/json;charset=utf-8");
method.setHeader("Accept", "application/json");
JSONObject param = new JSONObject();
method.setEntity(new StringEntity(param.toString(), "UTF-8"));
CloseableHttpResponse response = null;
response = httpClient.execute(method);
int status = response.getStatusLine().getStatusCode();
if (status == HttpStatus.SC_OK) {
String body = EntityUtils.toString(response.getEntity());
if(StrUtil.isNotBlank(body)){
System.out.println("body: "+body);
}
}
response.close();
} finally {
httpClient.close();
}