我試圖對需要證書的服務發出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