RestTemplate配置及如何支持https接口的访问

配置

@Configuration
public class RestTemplateConfig {

    @Bean
    public RestTemplate restTemplate() {
        SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
        factory.setConnectTimeout(30 * 1000);
        factory.setReadTimeout(60 * 1000);
        return new RestTemplate(factory);
    }

    public static HttpComponentsClientHttpRequestFactory generateHttpRequestFactory()
            throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException
    {
        TrustStrategy acceptingTrustStrategy = (x509Certificates, authType) -> true;
        SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, acceptingTrustStrategy).build();
        SSLConnectionSocketFactory connectionSocketFactory = new SSLConnectionSocketFactory(sslContext, new NoopHostnameVerifier());

        HttpClientBuilder httpClientBuilder = HttpClients.custom();
        httpClientBuilder.setSSLSocketFactory(connectionSocketFactory);
        CloseableHttpClient httpClient = httpClientBuilder.build();
        HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory();
        factory.setHttpClient(httpClient);
        return factory;
    }
}

普通http的使用方式

@Autowired
private RestTemplate restTemplate;

HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
Map<String,String> map = Maps.newHashMap();
map.put("imageData", base64);
HttpEntity<Map<String,String>> httpEntity = new HttpEntity<>(map, headers);
httpsRestTemplate.getMessageConverters().set(1, new StringHttpMessageConverter(StandardCharsets.UTF_8));
ResponseEntity<String> resp = httpsRestTemplate.exchange(uploadImageUrl, HttpMethod.POST, httpEntity, String.class);

支持https的使用方式

RestTemplate restTemplate= new RestTemplate(RestTemplateConfig.generateHttpRequestFactory());
上一篇:c++ 04 std::string


下一篇:计算机网络_04 网络层