RestTemplate
를 활용하여 또 다른 서버에 요청을 해야하는데 SSL 인증서 오류가 발생- unable to find valid certification path to requested target
ssl ignore 하는방법
다음 dependency를 추가해준다
// https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient
implementation 'org.apache.httpcomponents:httpclient:4.5.13'
RestTemplate Bean
을 추가해준다@Bean
public RestTemplate restTemplate() 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);
return restTemplate;
}
@Component
@RequiredArgsConstructor
public class MyService {
private final RestTemplate restTemplate;
public ResultDto testMethod(RequestDto dto){
URI uri = UriComponentsBuilder
.fromUriString("https://velog.pang.com") // 연결할 baseURL
.path("/server") // 연결 path
.encode()
.build()
.toUri();
RequestEntity<RequestDto> requestEntity =
RequestEntity
.post(uri)
.contentType(MediaType.APPLICATION_JSON)
.header("Authorization-Type", "User") // 삽입하고 싶은 header
.body(dto);
ResponseEntity<ResultDto> response =
restTemplate.exchange(requestEntity, ResultDto.class); // exchange(변환에 사용할 객체, 변환될 객체 타입)
return response.getBody();
}
}
그리고 출력결과가 잘 나오는지 테스트했는데 맵핑 실패..
처음에 만들어 놓았던 RestTemplate Bean
에 Jackson 맵핑 추가를 해준다
@Bean
public ObjectMapper objectMapper(){
ObjectMapper mapper = new ObjectMapper();
mapper.configure(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES, true);
return mapper;
}
@Bean
public MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter(){
MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
converter.setObjectMapper(objectMapper());
return converter;
}
@Bean
public RestTemplate restTemplate() throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException {
...
// convert 추가
restTemplate.getMessageConverters().add(0, mappingJackson2HttpMessageConverter());
return restTemplate;
}