rest template 发送 https post请求 Java代码示例
时间: 2023-06-01 14:06:33 浏览: 112
好的,关于发起 HTTPS POST 请求,可以使用 Spring Framework 中的 RestTemplate,以下是示例代码:
```
public String sendPostRequest(String url, String body, HttpHeaders headers) {
RestTemplate restTemplate = new RestTemplate(createSecureTransport());
HttpEntity<String> requestEntity = new HttpEntity<>(body, headers);
ResponseEntity<String> responseEntity = restTemplate.postForEntity(url, requestEntity, String.class);
return responseEntity.getBody();
}
private HttpComponentsClientHttpRequestFactory createSecureTransport() {
SSLContext sslContext = SSLContextBuilder.create()
.loadTrustMaterial(new TrustSelfSignedStrategy())
.build();
SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(sslContext,
NoopHostnameVerifier.INSTANCE);
Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
.register("https", socketFactory)
.build();
PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
return new HttpComponentsClientHttpRequestFactory(HttpClients.custom().setSSLSocketFactory(socketFactory)
.setConnectionManager(connectionManager).build());
}
```
这个示例代码使用了 RestTemplate 发起 HTTPS POST 请求,同时也实现了 SSL 安全连接,具体使用可以根据你的场景进行调整。
阅读全文