之前代码连接对端接口,证书认证失败,报错如下:
javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
之前代码如下:
public static HttpResponse request(String json,Map<String,String> headers,InterfaceAdapter in){
try{
ifToken(in,headers);
if(Objects.equals(in.getObject(), "2")){
//objectTwo
String url2 = in.getInterfaceOutput();
return doPostJson(url2,json,headers);
}else{
JSONObject result = new JSONObject();
result.put("message","object字段缺失");
result.put("code", 500);
return new HttpResponse(500,result.toJSONString());
}
}catch(Exception e){
e.printStackTrace();
JSONObject result = new JSONObject();
result.put("message","http-request报错"+e.getCause().getMessage());
result.put("code", 500);
return new HttpResponse(500,result.toJSONString());
}
}
修改后的代码
public static HttpResponse request(String paramMap,Map<String, String> headers,InterfaceAdapter in) {
try{
ifToken(in,headers);
String url2 = in.getInterfaceOutput();
log.info("objectTwo=>"+"object:"+in.getObject()+"URL:"+url2+"入参:"+JSONObject.parseObject(paramMap));
// 如果是Https请求
if (url2.startsWith(Const.HTTPS)) {
getTrust();
}
Connection connection = Jsoup.connect(url2);
connection.method(Connection.Method.POST);
connection.timeout(Const.TIME_OUT);
connection.ignoreHttpErrors(true);
connection.ignoreContentType(true);
connection.maxBodySize(0);
if (null != headers) {
connection.headers(headers);
}
connection.requestBody(paramMap);
Connection.Response execute = connection.execute();
log.info("post方法请求出参状态码"+execute.statusCode());
log.info("post方法请求出参"+execute.body());
return new HttpResponse(execute.statusCode(),execute.body());
}catch(Exception e){
e.printStackTrace();
JSONObject result = new JSONObject();
result.put("message","http-request报错"+e.getCause().getMessage());
result.put("code", 500);
return new HttpResponse(500,result.toJSONString());
}
}
获取服务器信任代码:
/**
* 获取服务器信任
*/
private static void getTrust(){
try {
HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
@Override
public boolean verify(String s, SSLSession sslSession) {
return true;
}
});
SSLContext sslContext = SSLContext.getInstance("SSL");
sslContext.init(null,new X509TrustManager[]{ new X509TrustManager() {
@Override
public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
}
@Override
public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
}
@Override
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[0];
}
}},new SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory());
} catch (Exception e) {
e.printStackTrace();
}
}