在使用Springboot的RestTemplate時(shí)候,我需要調(diào)用一個(gè)以Https開(kāi)頭的鏈接际乘,遇到了如下報(bào)錯(cuò)
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
大意就是我這個(gè)是https的請(qǐng)求,比較安全漂佩,需要跟服務(wù)器建立鏈接脖含,但是呢你又沒(méi)有證書(shū)所以我就報(bào)錯(cuò)了。
如果需要證書(shū)投蝉,并且服務(wù)器是有這個(gè)東西养葵,那么你就可以去找證書(shū)并且實(shí)現(xiàn)即可,如果你沒(méi)有證書(shū)不想做這個(gè)東西那么我們就采取禁用ssl證書(shū)這樣的方式來(lái)做了瘩缆。
主方法:
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("開(kāi)始第{}次使用定時(shí)器关拒!",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.");
}
}