The Apache HTTP Client is a very robust library, suitable for both simple and advanced use cases when testing HTTP endpoints. Check out our guide covering basic request and response handling, as well as security, cookies, timeouts, and more:
Mocking is an essential part of unit testing, and the Mockito library makes it easy to write clean and intuitive unit tests for your Java code.
Get started with mocking and improve your application tests using our Mockito guide:
Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.
Get started with understanding multi-threaded applications with our Java Concurrency guide:
Spring 5 added support for reactive programming with the Spring WebFlux module, which has been improved upon ever since. Get started with the Reactor project basics and reactive programming in Spring Boot:
Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.
But these can also be overused and fall into some common pitfalls.
To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:
Get started with Spring and Spring Boot, through the Learn Spring course:
>> LEARN SPRINGExplore Spring Boot 3 and Spring 6 in-depth through building a full REST API with the framework:
Yes, Spring Security can be complex, from the more advanced functionality within the Core to the deep OAuth support in the framework.
I built the security material as two full courses - Core and OAuth, to get practical with these more complex scenarios. We explore when and how to use each feature and code through it on the backing project.
You can explore the course here:
Spring Data JPA is a great way to handle the complexity of JPA with the powerful simplicity of Spring Boot.
Get started with Spring Data JPA through the guided reference course:
Refactor Java code safely β and automatically β with OpenRewrite.
Refactoring big codebases by hand is slow, risky, and easy to put off. Thatβs where OpenRewrite comes in. The open-source framework for large-scale, automated code transformations helps teams modernize safely and consistently.
Each month, the creators and maintainers of OpenRewrite at Moderne run live, hands-on training sessions β one for newcomers and one for experienced users. Youβll see how recipes work, how to apply them across projects, and how to modernize code with confidence.
Join the next session, bring your questions, and learn how to automate the kind of work that usually eats your sprint time.
1. Overview
In this tutorial, weβll see how to consume a REST service secured with HTTPS using Springβs RestTemplate.
2. Setup
We know that to secure a REST service, we need a certificate and a keystore generated from a certificate. We can get certificates from Certification Authorities (CA) to ensure that the application is secure and trusted for production-grade applications.
For this articleβs purpose, weβll use a self-signed certificate in our sample application.
Weβll use Springβs RestTemplate to consume an HTTPS REST service.
First, letβs create a controller class, WelcomeController, and a /welcome endpoint which returns a simple String response:
@RestController
public class WelcomeController {
@GetMapping(value = "/welcome")
public String welcome() {
return "Welcome To Secured REST Service";
}
}
Then, letβs add our keystore in the src/main/resources folder:
π secure cert resource folderNext, letβs add keystore-related properties to our application.properties file:
server.port=8443
server.servlet.context-path=/
# The format used for the keystore
server.ssl.key-store-type=PKCS12
# The path to the keystore containing the certificate
server.ssl.key-store=classpath:keystore/baeldung.p12
# The password used to generate the certificate
server.ssl.key-store-password=password
# The alias mapped to the certificate
server.ssl.key-alias=baeldung
We can now access the REST service at this endpoint: https://localhost:8443/welcome
3. Consuming Secured REST Service
Spring provides a convenient RestTemplate class to consume REST services.
While itβs straightforward to consume a simple REST service, when consuming a secured one, we need to customize the RestTemplate with the certificate/keystore used by the service.
Next, letβs create a simple RestTemplate object and customize it by adding the required certificate/keystore.
3.1. Create a RestTemplate Client
Letβs write a simple controller that uses a RestTemplate to consume our REST service:
@RestController
public class RestTemplateClientController {
private static final String WELCOME_URL = "https://localhost:8443/welcome";
@Autowired
private RestTemplate restTemplate;
@GetMapping("/welcomeclient")
public String greetMessage() {
String response = restTemplate.getForObject(WELCOME_URL, String.class);
return response;
}
}
If we run our code and access the /welcomeclient endpoint, weβll get an error since a valid certificate to access the secured REST Service wonβt be found:
javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed:
sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested
target at sun.security.ssl.Alerts.getSSLException(Alerts.java:192)
Next, weβll see how to resolve this error.
3.2. Configuring the RestTemplate for HTTPS Access
The client application accessing the secured REST service should contain a secure keystore in its resources folder. Further, the RestTemplate itself needs to be configured.
First, letβs add the keystore baeldung.p12 from earlier as the truststore in the /src/main/resources folder:
π Keystore in resource folderNext, we need to add the truststore details in the application.properties file:
server.port=8082
#trust store location
trust.store=classpath:keystore/baeldung.p12
#trust store password
trust.store.password=password
Finally, letβs customize the RestTemplate by adding the truststore:
@Configuration
public class CustomRestTemplateConfiguration {
@Value("${trust.store}")
private Resource trustStore;
@Value("${trust.store.password}")
private String trustStorePassword;
@Bean
public RestTemplate restTemplate() throws KeyManagementException, NoSuchAlgorithmException, KeyStoreException, CertificateException, MalformedURLException, IOException {
SSLContext sslContext = new SSLContextBuilder()
.loadTrustMaterial(trustStore.getURL(), trustStorePassword.toCharArray()).build();
SSLConnectionSocketFactory sslConFactory = new SSLConnectionSocketFactory(sslContext);
HttpClientConnectionManager cm = PoolingHttpClientConnectionManagerBuilder.create()
.setSSLSocketFactory(sslConFactory)
.build();
CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(cm).build();
ClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(httpClient);
return new RestTemplate(requestFactory);
}
}
Letβs understand the important steps in restTemplate() method above in detail.
First, we create an SSLContext object that represents a secure socket protocol implementation. We use the SSLContextBuilder classβs build() method to create it.
We use the SSLContextBuilderβs loadTrustMaterial() method to load the keystore file and credentials into the SSLContext object.
Then, we create SSLConnectionSocketFactory, a layered socket factory for TSL and SSL connections, by loading SSLContext. The purpose of this step is to verify that the server is using the list of trusted certificates we loaded in the previous step, i.e., to authenticate the server.
Now we can use our customized RestTemplate to consume secured REST service at the endpoint: http://localhost:8082/welcomeclient:
π Secured Rest Service By Customized Rest template Response
4. Conclusion
In this article, we discussed how to consume a secured REST service using a customized RestTemplate.
