发现报错unable to find valid certification path to requested target , 使用postman调用接口,设置忽略ssl证书接口有响应数据
项目中需要设置忽略ssl证书验证
1.创建连接
//创建忽略ssl连接
org.apache.http.client.HttpClient httpclient = HttpUtils.getHttpClient(url);
if (url.startsWith("https://")) {
SSLSocketFactory.getSocketFactory().setHostnameVerifier(new AllowAllHostnameVerifier());
}
HttpPost post = new HttpPost(url);
List<NameValuePair> qparams = new ArrayList<NameValuePair>();
qparams.add(new BasicNameValuePair("PROJECT_CODE", PROJECT_CODE));
qparams.add(new BasicNameValuePair("LICENSE_KEY", "FF72F9F2-F588-437E-A015-9DE56A1E004E"));
post.setEntity(new UrlEncodedFormEntity(qparams, HTTP.UTF_8));
HttpResponse response = httpclient.execute(post);
HttpEntity entity = response.getEntity();
String result = "";
if (entity != null) {
result = EntityUtils.toString(entity);
}
//getHttpClient方法
public static HttpClient getHttpClient(String url) {
HttpClient httpClient = HttpClientBuilder.create().build();
if (url.startsWith("https")) {
httpClient = getHttpClient();
}
return httpClient;
}
private static CloseableHttpClient getHttpClient() {
RegistryBuilder<ConnectionSocketFactory> registryBuilder = RegistryBuilder.<ConnectionSocketFactory>create();
ConnectionSocketFactory plainSF = new PlainConnectionSocketFactory();
registryBuilder.register("http", plainSF);
//指定信任密钥存储对象和连接套接字工厂
try {
KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
//信任任何链接
TrustStrategy anyTrustStrategy = new TrustStrategy() {
@Override
public boolean isTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
return true;
}
};
SSLContext sslContext = SSLContexts.custom().useTLS().loadTrustMaterial(trustStore, anyTrustStrategy).build();
LayeredConnectionSocketFactory sslSF = new SSLConnectionSocketFactory(sslContext, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
registryBuilder.register("https", sslSF);
} catch (KeyStoreException e) {
throw new RuntimeException(e);
} catch (KeyManagementException e) {
throw new RuntimeException(e);
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException(e);
}
Registry<ConnectionSocketFactory> registry = registryBuilder.build();
//设置连接管理器
PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(registry);
// connManager.setDefaultConnectionConfig(connConfig);
// connManager.setDefaultSocketConfig(socketConfig);
//构建客户端
return HttpClientBuilder.create().setConnectionManager(connManager).build();
}