在使用Springboot的RestTemplate时候,我需要调用一个以Https开头的链接,遇到了如下报错
org.springframework.web.client.ResourceAccessException: I/O error on
GET request for "": sun.security.validator.ValidatorException: PKIX path
building failed: sun.security.provider.certpath.SunCertPathBuilderException:
unable to find valid certification path to requested target; nested exception
is 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
大意就是我这个是https的请求,比较安全,需要跟服务器建立链接,但是呢你又没有证书所以我就报错了。
如果需要证书,并且服务器是有这个东西,那么你就可以去找证书并且实现即可,如果你没有证书不想做这个东西那么我们就采取禁用ssl证书这样的方式来做了。
主方法:
public void start(){
RestTemplate restTemplate = new RestTemplate();
try {
SSLValidation.turnOffSslChecking();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (KeyManagementException e) {
e.printStackTrace();
}
String url = cloudUrlConfig.getUrl()+ENABLE_RULE_URL;
ResultDto resultDto =
restTemplate.getForObject(url,ResultDto.class)
i++;
log.info("开始第{}次使用定时器!",i);
}
禁用ssl方法
import javax.net.ssl.*;
import java.security.*;
import java.security.cert.X509Certificate;
public class SSLValidation {
private static final TrustManager[] UNQUESTIONING_TRUST_MANAGER = new TrustManager[]{
new X509TrustManager() {
public java.security.cert.X509Certificate[] getAcceptedIssuers(){
return null;
}
public void checkClientTrusted( X509Certificate[] certs, String authType ){}
public void checkServerTrusted( X509Certificate[] certs, String authType ){}
}
};
public static void turnOffSslChecking() throws NoSuchAlgorithmException, KeyManagementException {
// Install the all-trusting trust manager
final SSLContext sc = SSLContext.getInstance("SSL");
sc.init( null, UNQUESTIONING_TRUST_MANAGER, null );
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
}
public static void turnOnSslChecking() throws KeyManagementException, NoSuchAlgorithmException {
// Return it to the initial state (discovered by reflection, now hardcoded)
SSLContext.getInstance("SSL").init( null, null, null );
}
private SSLValidation(){
throw new UnsupportedOperationException( "Do not instantiate libraries.");
}
}