Backend/Spring

[Spring] RestTemplate에서 PATCH가 안 된다면? 원인과 해결 방법 정리

누구세연 2025. 3. 1. 17:44

RestTemplate를 사용하던 도중 PATCH 메서드를 호출할 때 아래와 같은 오류가 발생했습니다. 👀

org.springframework.web.client.ResourceAccessException: I/O error on PATCH request for “https://api.example.com/resource/1”: Invalid HTTP method: PATCH; nested exception is java.net.ProtocolException: Invalid HTTP method: PATCH

나는 위와 같은 오류를 경험했지만, PATCH 요청을 보낼 때 다음과 같은 다른 오류가 발생할 수도 있다고 합니다.

org.springframework.web.client.HttpClientErrorException$MethodNotAllowed: 405 Method Not Allowed

왜 이런 문제가 발생하는지 살펴보고 해결 방법을 정리해 보겠습니다. 👩🏻‍💻

 

 

발생한 오류 분석

🔍 문제 상황

Spring의 RestTemplate을 사용하여 PATCH 요청을 보낼 때, 다음과 같은 코드로 요청을 시도했습니다.

RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<String> requestEntity = new HttpEntity<>(jsonBody, headers);

ResponseEntity<String> response = restTemplate.exchange(
    "https://api.example.com/resource/1",
    HttpMethod.PATCH,
    requestEntity,
    String.class
);

이 코드를 실행하면 위에서 언급한 오류가 발생할 수 있습니다.

 

원인 분석

1️⃣  PATCH 메서드 지원 문제

  • RestTemplate은 내부적으로 HttpURLConnection을 사용합니다.
  • Java의 기본 HttpURLConnectionPATCH 요청을 직접 지원하지 않습니다.

2️⃣  HttpMessageConverter 미지원 문제

  • RestTemplatePATCH 요청을 처리할 때 적절한 HttpMessageConverter가 없어 오류가 발생할 수 있습니다.
  • PATCH 요청을 보낼 때, 기본 HttpMessageConverter가 JSON 데이터를 변환하는 방식을 제대로 지원하지 않는 경우가 있습니다.

 

해결 방법

방법 1: HttpComponentsClientHttpRequestFactory 사용

RestTemplate의 기본 구현체는 HttpURLConnection을 기반으로 동작하지만, Apache HttpClient를 사용하면 PATCH 요청을 정상적으로 처리할 수 있습니다.

RestTemplate restTemplate = new RestTemplate(new HttpComponentsClientHttpRequestFactory());

📌 이렇게 하면 PATCH 요청을 제대로 처리할 수 있습니다.

 

방법 2: RestTemplate 대신 WebClient 사용

Spring 5부터 제공되는 WebClient를 사용하면 PATCH 요청을 더 쉽게 처리할 수 있습니다.

WebClient webClient = WebClient.builder().build();

String response = webClient.patch()
    .uri("https://api.example.com/resource/1")
    .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
    .bodyValue(jsonBody)
    .retrieve()
    .bodyToMono(String.class)
    .block();

📌 WebClient는 비동기 방식이며, PATCH 요청을 기본적으로 지원하므로 더 적합합니다.

 

방법 3: HttpMessageConverter 수동 등록

RestTemplate restTemplate = new RestTemplate();
restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());

이렇게 하면 PATCH 요청에서 JSON 변환 문제를 방지할 수 있습니다.

 

 

RestTemplate은 기본적으로 PATCH 요청을 완벽히 지원하지 않는다는 사실을 알게 되었습니다.
Spring 5 이상을 사용한다면 WebClient를 사용하는 것이 더 직관적이고 안정적인 방법이며,
RestTemplate을 유지해야 한다면 HttpComponentsClientHttpRequestFactory를 적용하는 것이 가장 좋은 대안
이라고 생각합니다!
이제 PATCH 요청을 더 안정적으로 처리할 수 있을 것 입니다. 🚀