我试图对需要证书的服务发出https post请求。我已经获得了在SOAPUI和Postman中工作的相同请求。我还能够使用restTemplate获取其他非证书要求的POST请求以在Spring Boot中工作。然而,当我尝试做与restTemplate证书POST请求,我得到收到以下异常:Spring Boot restTemplate POST请求bad_certificate,但在SOAPUI和Postman中工作
http-nio-8080-exec-5, handling exception: javax.net.ssl.SSLHandshakeException: Received fatal alert: bad_certificate
2017-08-04 10:13:23.953 ERROR 54082 --- [nio-8080-exec-5] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.web.client.ResourceAccessException: I/O error on POST request for "htpps://...": Received fatal alert: bad_certificate; nested exception is javax.net.ssl.SSLHandshakeException: Received fatal alert: bad_certificate] with root cause
javax.net.ssl.SSLHandshakeException: Received fatal alert: bad_certificate
下面是原始请求SOAPUI使得它的工作原理:
POST https://... HTTP/1.1
Accept-Encoding: gzip,deflate
Content-Type: application/json
Content-Length: 0
Host: ...
Connection: Keep-Alive
User-Agent: Apache-HttpClient/4.1.1 (java 1.5)
下面是相关春启动代码,这不工作
// request info
logger.info("enter");
String endpoint = "https://...";
String certFileName = "src/main/resources/keystore.jks";
String pass = "tempPass";
String body = "{}";
// set up cert
logger.info("begin load cert");
KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
keyStore.load(new FileInputStream(new File(certFileName)), pass.toCharArray());
SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(new SSLContextBuilder().loadTrustMaterial(null, new TrustSelfSignedStrategy()).loadKeyMaterial(keyStore, pass.toCharArray()).build());
HttpClient httpClient = HttpClients.custom().setSSLSocketFactory(socketFactory).build();
ClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(httpClient);
// set up request
logger.info("setup request");
RestTemplate restTemplate = new RestTemplate(requestFactory);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<String> entity = new HttpEntity<>(body);
// make request
logger.info("make request");
ResponseEntity<Object> res = restTemplate.postForEntity(endpoint, entity, Object.class);
// ResponseEntity<Object> res = restTemplate.exchange(endpoint, HttpMethod.POST, entity, Object.class);
// handle output
logger.info("received output");
if (res.getStatusCode().is2xxSuccessful())
return res.getBody().toString();
else
return res.getStatusCode().toString();
进一步了解详细: 我不知道这事,但我也试过-Dtrust_all_cert=true
标志,但结果相同。我也尝试了-Djavax.net.debug=all
标志,但所有的输出看起来都很成功。如果它有帮助,我可以包含调试,但它们很长。我没有其他配置设置特定于此证书POST请求。
我正在使用Java 1.8。
我要补充,我的代码证书的部分,我从一个答案抄在Spring Boot restTemplate POST request bad_certificate, but works in SOAPUI and Postman