Skip to content

Instantly share code, notes, and snippets.

@edwardoboh
Created December 10, 2024 15:37
Show Gist options
  • Save edwardoboh/c66b5b4d5b3c3b3e17edfbb4650e98e9 to your computer and use it in GitHub Desktop.
Save edwardoboh/c66b5b4d5b3c3b3e17edfbb4650e98e9 to your computer and use it in GitHub Desktop.
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
import org.apache.http.ssl.SSLContextBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;

import javax.net.ssl.SSLContext;
import java.io.File;

@Configuration
public class RestTemplateConfig {

    @Bean
    public RestTemplate restTemplate() throws Exception {
        String trustStorePath = "src/main/resources/truststore.jks";
        String trustStorePassword = "changeit";

        SSLContext sslContext = SSLContextBuilder.create()
                .loadTrustMaterial(new File(trustStorePath), trustStorePassword.toCharArray())
                .build();

        CloseableHttpClient httpClient = HttpClients.custom()
                .setSSLSocketFactory(new SSLConnectionSocketFactory(sslContext))
                .build();

        HttpComponentsClientHttpRequestFactory requestFactory =
                new HttpComponentsClientHttpRequestFactory(httpClient);

        return new RestTemplate(requestFactory);
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment