티스토리 뷰

1. Header Content-type과 Accept의 이해 

Content-type은 Http 통신에서 메시지를 전달할 때  request body의 데이터 형식을 의미한다. 

"이런 형식으로 전달하니 받으세요" 라는 의미이다. 

key=value 형식에서는 아무 의미가 없으며 content-type을 지정하지 않으면 일반 텍스트로 인식한다. 

Accept는 서버에서 결과를 줄 때 "이런 형식으로 내려 주세요" 라는 의미이다. 

 

2. dependency 추가 

<dependency>
    <groupId>com.fasterxml.jackson.dataformat</groupId>
    <artifactId>jackson-dataformat-xml</artifactId>
</dependency>

xml 형식으로 데이터를 반환하기 위해서 필요한 라이브러리이다. 

Accept 지정없이 요청을 하면 결과 값이 xml로 반환된다. 

3. 테스트 

@Slf4j
@RestController
@RequestMapping("/controller/response")
public class ResponseAPIController {

    /**
     * Content-type 정보가 없을 때 String으로 받기  
     * @return
     */
    @PostMapping("/contentTypeNone")
    public ResponseEntity<String> contentTypeNoneString(@RequestBody final String body) {
        log.debug("requestParamRequiredFalse call : "+body);
        return ResponseEntity.ok(body);
    }

    /**
     * Content-type 정보가 없을 때 객체로 받기 - 에러 발생   
     * @param body
     * @return
     */
    @PostMapping("/contentTypeNonObject")
    public ResponseEntity<ResponseTest> contentTypeNone(@RequestBody final ResponseTest body) {
        log.debug("requestParamRequiredFalse call : "+body);
        return ResponseEntity.ok(body);
    }

    @Getter
    @Setter
    @ToString
    public static class ResponseTest {
        
        private String id;
        private String name;
        private Boolean test;
        private Date created;

        public ResponseTest() {
            super();
        }

        public ResponseTest(String id, String name, boolean test, Date created) {
            super();
            this.id = id;
            this.name = name;
            this.test = test;
            this.created = created;
        }
    }

}

content-type 없이 json 형태의 값을 전달하고 텍스트로 받는 경우

 

content-type 없이 json 형태의 값을 전달하고 객체로 받는 경우
Content-type을 입력한 경우
Accept 헤더를 추가한 경우 json으로 결과가 내려온걸 확인할 수 있다.

produces 지정 테스트 

    /**
     * Content-type : application/json, 결과는 xml   
     * @param body
     * @return
     */
    @PostMapping(path="/producesXml",  produces="application/xml; charset=UTF8")
    public ResponseEntity<ResponseTest> producesXml(@RequestBody final ResponseTest body) {
        log.debug("requestParamRequiredFalse call : "+body);
        return ResponseEntity.ok(body);
    }
    
    /**
     * Content-type : application/json, 결과는 json   
     * @param body
     * @return
     */
    @PostMapping(path="/producesJson",  produces="application/json; charset=UTF8")
    public ResponseEntity<ResponseTest> producesJson(@RequestBody final ResponseTest body) {
        log.debug("requestParamRequiredFalse call : "+body);
        return ResponseEntity.ok(body);
    }

produces="application/xml; charset=UTF8" 추가 후 테스트 

Accept 지정을 하지 않더라도 xml로 내려 간다.

 

Accept 지정을 안 해도 json 형태로 내려 간다.

 

댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/04   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30
글 보관함