下面是例子,如何做到這一點使用RestTemplate和Apache HttpClient
你應該定義自己的RestTemplate
與配置SSL上下文:
@Bean
public RestTemplate restTemplate(RestTemplateBuilder builder) throws Exception {
char[] password = "password".toCharArray();
SSLContext sslContext = SSLContextBuilder.create()
.loadKeyMaterial(keyStore("classpath:cert.jks", password), password)
.loadTrustMaterial(null, new TrustSelfSignedStrategy()).build();
HttpClient client = HttpClients.custom().setSSLContext(sslContext).build();
return builder
.requestFactory(new HttpComponentsClientHttpRequestFactory(client))
.build();
}
private KeyStore keyStore(String file, char[] password) throws Exception {
KeyStore keyStore = KeyStore.getInstance("PKCS12");
File key = ResourceUtils.getFile(file);
try (InputStream in = new FileInputStream(key)) {
keyStore.load(in, password);
}
return keyStore;
}
現在此模板執行的所有遠程呼叫都將使用cert.jks
進行簽名。 注意:你會需要把cert.jks
到你的classpath
@Autowired
private RestTemplate restTemplate;
public List<Info> getInfo() throws RestClientException, URISyntaxException {
HttpEntity<?> httpEntity = new HttpEntity<>(null, new HttpHeaders());
ResponseEntity<Info[]> resp = restTemplate.exchange(
new URI(BASE_URL + "/Info"), HttpMethod.GET,
httpEntity, Info[].class);
return Arrays.asList(resp.getBody());
}
的偉大工程的感謝! – Nas3nmann