새소식

반응형
WEB/Spring

[Spring] HttpServletRequest 로 Body 내용 가져오기[json]

  • -
반응형

2022-05-06


Photo by Benoît Deschasaux on Unsplash

기존에 @RequestBody 어노테이션을 사용하다가, content-type이 text/plain 형식의 json 데이터를 처리해야 하는데, [org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'text/plain;charset=UTF-8' not supported]  같은 오류가 발생하였으며, 이를 해결하는 방법을 찾아 공유하고자 한다. 방법은 아래와 같다.


- 코드

	@RequestMapping(value="/")
	public void test(HttpServletRequest request){     
		//body에 있는 제이슨을 받은 객체
		String bodyJson = "";
        
		StringBuilder stringBuilder = new StringBuilder();
        BufferedReader br = null;
        //한줄씩 담을 변수
        String line = "";
        
        try {
        	//body내용 inputstream에 담는다.
            InputStream inputStream = request.getInputStream();
            if (inputStream != null) {
                br = new BufferedReader(new InputStreamReader(inputStream));
                //더 읽을 라인이 없을때까지 계속
                while ((line = br.readLine()) != null) {
                    stringBuilder.append(line);
                }
            }else {
            	log.info("Data 없음");
            }
        } catch (IOException e) {
        	e.printStackTrace();
        } 
 
        bodyJson = stringBuilder.toString();
		JSONParser jsonParser = new JSONParser();
		JSONObject jsonObject = null;
		try {
	        //json 형태로 변환하기
			jsonObject = (JSONObject) jsonParser.parse(bodyJson);
		} catch (ParseException e) {
			e.printStackTrace();
		}
        log.info(jsonObject.toJSONString());
	}

(log.info는 class 단에서 @Slf4j 어노테이션을 사용했다.) 이와 같은 방법은 HttpServletRequest에서 inputStream으로 body 값을 String으로 내려받아 이를 다시 jsonobject로 변환하는 방법이다. 코드 자체는 크게 어렵지 않으나, 직접 코드를 작성해야 하기 때문에 어노테이션 하나로 처리하는 과정보다 조금은 번거로울 수 있다.


메인 이미지 출처 : Photo by Benoît Deschasaux on Unsplash  

반응형
Contents

포스팅 주소를 복사했습니다

이 글이 도움이 되었다면 공감 부탁드립니다.