Recently I was trying to write integration tests using Spring’s RestTemplate to make REST calls to an integration server. The server was secured using basic auth over https, and the SSL certificate was a self-signed cert created for development use only. I wanted to use RestTemplate to retrieve JSON objects and convert them to POJO’s for asserting values in the test. However it turned out that most of the examples online did not deal with this particular scenario or were out of date. So here is how to use Spring 4’s RestTemplate with the latest Apache HTTPClient (version 4.3.1 as of this writing) over HTTPS.
One complication was that the cert was self-signed. This is easily acceptable if using curl with the “-k” option, but with RestTemplate it requires a little more work to accept the cert.
Spring’s RestTemplate integrates with Apache HttpClient, it’s just the HttpClient that needs to be configured with the username, password, and to accept an insecure cert. Here is the code:
SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, new TrustSelfSignedStrategy()).useTLS().build(); SSLConnectionSocketFactory connectionFactory = new SSLConnectionSocketFactory(sslContext, new AllowAllHostnameVerifier()); BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("username", "mypassword")); HttpClient httpClient = HttpClientBuilder.create() .setSSLSocketFactory(connectionFactory) .setDefaultCredentialsProvider(credentialsProvider) .build(); ClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(httpClient);
Finally, the request factory is used to construct a new RestTemplate which can make the call to the server.
RestTemplate template = new RestTemplate(requestFactory); ResponseEntity<User> response = template.postForEntity("https://localhost:8000/path/to/user/1", "", User.class); User userResponse = response.getBody(); assertEquals(1L, userResponse.getId());
Fortunately the test passes… now we can run integration tests with JUnit at will! Happy Testing!