RestTemplate a widely used client tool from Spring framework. Here are some useful hints when using Spring RestTemplate.
- How to use basic authentication with RestTemplate?
- How to add arbitrary Http header, e.g.”Content-Type”, “Accept”, with RestTemplate?
- How to bypass(not solve) Https error “java.security.cert.CertificateException: No name matching <some url> found”?
1. Basic authentication for RestTemplate
RestTemplate restTemplate = new RestTemplate(); // set username/password for http basic authentication restTemplate.getInterceptors().add(new BasicAuthorizationInterceptor("myUserName","myPassword")); // use restTemplate to send requst // .....
2. Add arbitrary http header for RestTemplate
Like above for adding basic authentication, this time need your own ClientHttpRequestInterceptor implementation. (BasicAuhorizationInterceptor for basic authentication is already predefined in spring).
RestTemplate restTemplate = new RestTemplate(); // set content-type=application/json http header restTemplate.getInterceptors().add(new ClientHttpRequestInterceptor() { @Override public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException { request.getHeaders().add("Content-Type", MediaType.APPLICATION_FORM_URLENCODED.toString()); return execution.execute(request, body); } }); // use restTemplate to send requst // .....
For java8 +, using lamda can make it look more neat. Functionally they are equivalent.
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 // .....
Above example add content-type to http header, it can be used to add anything you like to http header.
3. Bypass Https error “java.security.cert.CertificateException: No name matching <some url> found”
When use RestTemplate to access resource with protocol https, it may has the exception complain something like “java.security.cert.CertificateException: No name matching <some url> found”. This is because the java applicatoin doesn’t has the right certification in its keystore. As a developer you probably don’t want to get blocked when someone is working on the CA procedure. You can continue by ignore this SSL host verification like below. But this is only a temporary solution, should not be used on any production environment.
@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); } }
Then inject your own RestTemplate bean and send https requests, the Exception will gone. But again this is only a bypass, not a final solution for this Exception.
0 comments:
Post a Comment