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.

Revisions

  1. edwardoboh created this gist Dec 10, 2024.
    40 changes: 40 additions & 0 deletions java_ssl.md
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,40 @@


    ```java
    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);
    }
    }

    ```