RestTemplate
으로 HTTPS가 적용되어 있는 사이트를 호출하는 경우 인증서에 대한 유효성 검사가 이루어져야 하지만 이를 무시하고 HTTPS로 호출하고자 하는 경우 다음과 같이 코드를 작성할 수 있습니다.
import org.apache.http.conn.ssl.SSLConnectionSocketFactory; import org.apache.http.conn.ssl.TrustStrategy; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.springframework.http.ResponseEntity; import org.springframework.http.client.HttpComponentsClientHttpRequestFactory; import org.springframework.web.client.RestTemplate; import javax.net.ssl.SSLContext; import java.security.KeyManagementException; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; import java.security.cert.X509Certificate; public class Tester { public static void main(String[] args) throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException { TrustStrategy acceptingTrustStrategy = (X509Certificate[] chain, String authType) -> true; SSLContext sslContext = org.apache.http.ssl.SSLContexts.custom() .loadTrustMaterial(null, acceptingTrustStrategy) .build(); SSLConnectionSocketFactory csf = new SSLConnectionSocketFactory(sslContext); CloseableHttpClient httpClient = HttpClients.custom() .setSSLSocketFactory(csf) .build(); HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(); requestFactory.setHttpClient(httpClient); RestTemplate restTemplate = new RestTemplate(requestFactory); ResponseEntity<String> forEntity = restTemplate.getForEntity("https://www.amazon.com/", String.class); System.out.println(forEntity.getBody()); } }
이 코드가 동작하려면 Maven POM에 다음을 추가해야 합니다.
<dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.5.12</version> </dependency>
1 개의 댓글
Edward 저자
5월 30, 2020Spring Boot에 SSL 적용하는 방법은 https://www.securesign.kr/guides/Spring-Boot-SSL-Certificate-Install에 있습니다.