问题:在http请求https接口过程中经常会遇到SSL证书检查或者证书过期
** sun.security.validator.ValidatorException: PKIX path validation failed: java.security.cert.CertPathValidatorException: validity check failed **
解决办法:绕过证书检查
代码如下:
public static byte[] getFile(String url) throws Exception {
log.info("get file url:"+url);
try {
/*HttpClientBuilder builder = HttpClients.custom();
builder.setSSLHostnameVerifier((hostName, sslSession) -> {
return true; // 证书校验通过
});*/
//CloseableHttpClient httpclient = builder.build();
//CloseableHttpClient httpclient = createSSLClientDefault();
DefaultHttpClient httpclient = new DefaultHttpClient();
enableSSL(httpclient);
HttpGet request = new HttpGet(url);
CloseableHttpResponse response = httpclient.execute(request);
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == HttpStatus.SC_OK) {
HttpEntity entity = response.getEntity();
if(entity == null) return null;
byte[] imgByte = EntityUtils.toByteArray(entity);
return imgByte;
}
}catch (Exception ex){
log.error("get file error:"+ex.getMessage());
ex.printStackTrace();
throw ex;
}
return null;
}
/**
* 访问https的网站
* @param httpclient
*/
private static void enableSSL(DefaultHttpClient httpclient){
//调用ssl
try {
SSLContext sslcontext = SSLContext.getInstance("TLS");
sslcontext.init(null, new TrustManager[] { truseAllManager }, null);
SSLSocketFactory sf = new SSLSocketFactory(sslcontext);
sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
Scheme https = new Scheme("https", sf, 443);
httpclient.getConnectionManager().getSchemeRegistry().register(https);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 重写验证方法,取消检测ssl
*/
private static TrustManager truseAllManager = new X509TrustManager(){
public void checkClientTrusted(
java.security.cert.X509Certificate[] arg0, String arg1)
throws CertificateException {
// TODO Auto-generated method stub
}
public void checkServerTrusted(
java.security.cert.X509Certificate[] arg0, String arg1)
throws CertificateException {
// TODO Auto-generated method stub
}
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
// TODO Auto-generated method stub
return null;
}
};
};