study/springboot
013. Content-type, Accept를 통한 요청 및 결과 처리
까오기
2022. 5. 16. 18:17
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;
}
}
}
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" 추가 후 테스트