Partner – Moderne – NPI EA (cat=Spring Boot)
announcement - icon

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.

Course – Black Friday 2026 – NPI EA – main – before_post_content
announcement - icon

Yes, we're now running our Black Friday Sale. All Courses are 33% off until 1st December, 2026 at 17:00 Romania time:

>> EXPLORE ACCESS NOW

Course – Black Friday 2026 – NPI – main – before_post_content
announcement - icon

Yes, we're now running our Black Friday Sale. All Courses are 33% off until 1st December, 2026 at 17:00 Romania time:

>> EXPLORE ACCESS NOW

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 folder

Next, 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 folder

Next, 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.

The code backing this article is available on GitHub. Once you're logged in as a Baeldung Pro Member, start learning and coding on the project.
Partner – Moderne – NPI EA (tag=Refactoring)
announcement - icon

Modern Java teams move fast — but codebases don’t always keep up. Frameworks change, dependencies drift, and tech debt builds until it starts to drag on delivery. OpenRewrite was built to fix that: an open-source refactoring engine that automates repetitive code changes while keeping developer intent intact.

The monthly training series, led by the creators and maintainers of OpenRewrite at Moderne, walks through real-world migrations and modernization patterns. Whether you’re new to recipes or ready to write your own, you’ll learn practical ways to refactor safely and at scale.

If you’ve ever wished refactoring felt as natural — and as fast — as writing code, this is a good place to start.

Course – Black Friday 2026 – NPI EA – main – after_post_content

announcement - icon

Yes, we're now running our Black Friday Sale. All Courses are 33% off until 1st December, 2026 at 17:00 Romania time:

>> EXPLORE ACCESS NOW

Course – Black Friday 2026 – NPI – main – after_post_content

announcement - icon

Yes, we're now running our Black Friday Sale. All Courses are 33% off until 1st December, 2026 at 17:00 Romania time:

>> EXPLORE ACCESS NOW

3 Comments
Oldest
Newest