ezhovdv
7/15/2018 - 7:04 PM

Spring rest-template custom processing

Spring rest-template custom processing

RestTemplate restTemplate = new RestTemplate();
 
// set content-type=application/json http header, use lamda 
restTemplate.getInterceptors().add((request, body, execution) -> {
  request.getHeaders().add("Content-Type", MediaType.APPLICATION_FORM_URLENCODED.toString());
  return execution.execute(request, body);
});
       
// use restTemplate to send requst
// .....
@Configuration
public class ByPassSSLVerificationConfig {
  // This RestTemplate actually ignore the SSL hostname verification
  @Bean
  public RestTemplate getRestTemplate() throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException {
    TrustStrategy acceptingTrustStrategy = (X509Certificate[] chain, String authType) -> true;
    HostnameVerifier allPassVerifier = (String s, SSLSession sslSession) -> true;  // ignore hostnaem checking
 
    SSLContext sslContext = org.apache.http.ssl.SSLContexts.custom()
        .loadTrustMaterial(null, acceptingTrustStrategy).build(); // keystore is null, not keystore is used at all
 
    SSLConnectionSocketFactory csf = new SSLConnectionSocketFactory(sslContext, allPassVerifier);
    CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(csf).build();
    HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
 
    requestFactory.setHttpClient(httpClient);
    return new RestTemplate(requestFactory);
  }
}