写了一个接口,在 sevice 层再去调用远程的一个接口,出现 ssh 证书的问题,代码如下:
String url = "远程请求地址";
HttpHeaders headers = new HttpHeaders();
Map<String, String> headerMap = ServerHttpUtil.getSign();
for (Map.Entry<String, String> entry : headerMap.entrySet()) {
headers.add(entry.getKey(), entry.getValue());
}
headers.setAccept(Collections.singletonList(MediaType.TEXT_HTML));
HttpEntity<String> entity = new HttpEntity<>(headers);
try {
RestTemplate restTemplate = new RestTemplate();
ResponseEntity<byte[]> exchange = restTemplate.exchange(url, HttpMethod.GET, entity, byte[].class);
headers = exchange.getHeaders();
for (Map.Entry<String, List<String>> header : headers.entrySet()) {
response.setHeader(header.getKey(), URLEncoder.encode(header.getValue().get(0), "ISO-8859-1"));
}
response.getOutputStream().write(exchange.getBody());
} catch (Exception e) {
System.out.println("下载失败:" + e);
}
出现了异常:
javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path validation failed: java.security.cert.CertPathValidatorException: validity check failed
at sun.security.ssl.Alert.createSSLException(Alert.java:131)
at sun.security.ssl.TransportContext.fatal(TransportContext.java:353)
at sun.security.ssl.TransportContext.fatal(TransportContext.java:296)
at sun.security.ssl.TransportContext.fatal(TransportContext.java:291)
at sun.security.ssl.CertificateMessage$T12CertificateConsumer.checkServerCerts(CertificateMessage.java:652)
at sun.security.ssl.CertificateMessage$T12CertificateConsumer.onCertificate(CertificateMessage.java:471)
at sun.security.ssl.CertificateMessage$T12CertificateConsumer.consume(CertificateMessage.java:367)
at sun.security.ssl.SSLHandshake.consume(SSLHandshake.java:376)
at sun.security.ssl.HandshakeContext.dispatch(HandshakeContext.java:444)
at sun.security.ssl.HandshakeContext.dispatch(HandshakeContext.java:422)
at sun.security.ssl.TransportContext.dispatch(TransportContext.java:183)
at sun.security.ssl.SSLTransport.decode(SSLTransport.java:154)
at sun.security.ssl.SSLSocketImpl.decode(SSLSocketImpl.java:1279)
at sun.security.ssl.SSLSocketImpl.readHandshakeRecord(SSLSocketImpl.java:1188)
at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:401)
at sun.security.ssl.SSLSocketImpl.ensureNegotiated(SSLSocketImpl.java:808)
at sun.security.ssl.SSLSocketImpl.access$200(SSLSocketImpl.java:75)
at sun.security.ssl.SSLSocketImpl$AppOutputStream.write(SSLSocketImpl.java:1093)
at java.io.BufferedOutputStream.flushBuffer(BufferedOutputStream.java:82)
我请求的地址是 https,需要 ssh 证书,还好远程接口也提供了 http 的地址,我改成请求 http 的地址后可以成功返回数据了。
也有其他的情况,比如证书过期,可以更新或者获取证书。