[Spring] http header Content-Type : form-urlencoded 과 RestTemplate 요청 자료형

Jinbro·2022년 5월 12일
0

Spring

목록 보기
3/5

이슈 : restTemplate 요청 파라미터 HashMap, DTO 전달 시 error 발생

// http header
HttpHeaders requestHeader = new HttpHeaders();
requestHeader.add("Content-Type", "application/x-www-form-urlencoded")
// http body
// 이슈 case 1 : HashMap (아래 error 호출)
Map<String, String> requestBody = new HashMap<>();
// 이슈 case 2 : dto (동일 error 호출)
// ReqDto requestBody = new ReqDto();
// call rest API
ResponseEntity<Map> responseEntity = restTemplate.exchange(url, HttpMethod.POST, requestHeader, requestBody, Map.class);
  • no httpmessageconverter for java.util.hashmap and content type application/x-www-form-urlencoded
    => application/x-www-form-urlencoded 미디어 타입의 경우, Request Body의 java 객체(HashMap, DTO)를 변환할 수 있는 converter가 없다.

Content-Type에 따른 Request Body 형식

// 1. application/json : json format
{
	"requestNo":"12345",
    "name":"Park"
}

// 2. application/x-www-form-urlencoded : k1=v1&k2=v2&k3=v3 format
requestNo=12345&name=Park
  1. json format : 정상
  2. form-urlencoded : 이슈 발생

솔루션 : MultiValueMap

MultiValueMap의 경우,
Spring Boot에서 FormHttpMessageConverter가 자동으로 request body의 MultiValueMap 객체를 application/x-www-form-urlencoded 형식으로 변환해준다.

// http body 선언
MultiValueMap<String, String> requestBody = new LinkedMultivalueMap<>();

참고

Post 요청과 Content-Type 관계
MultiValueMap 솔루션

profile
자기 개발 기록 저장소

0개의 댓글