일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 | 31 |
- 백준 16719
- 백준 15685
- Spring
- MySQL
- 파이썬
- java
- 백준 19238
- 프로그래머스
- spring oauth
- 백준 16235
- 웹어플리케이션 서버
- 백준
- Coroutine
- 백준 17779
- 백준 17626
- JPA
- 백준 파이썬
- sql 기술면접
- 백준 16236
- MSA
- re.split
- java 기술면접
- Kotlin
- 프로래머스
- spring cloud
- with recursive
- springboot
- Spring Boot
- spring security
- JVM
- Today
- Total
시작이 반
[Spring] RestTemplate (Content-Type에러) 본문
Spring 3.0부터 치원하는 http통신에서 유용하게 쓸 수 있는 템플릿이다.
json, xml응답을 모두 받을 수 있다.
Open API의 출력 형태가 Json이기 때문에 RestTemplate을 사용하였다.
처음으로 사용한 OpenAPI는 네이버 도서 검색 API였다. 하지만 이 API는 검색기능만 지원하였다. 책 분야별 전체 정보가 필요했다.
네이버 API사용 tmdrl5779.tistory.com/46
[Spring] 네이버 검색 API 사용
책 검색 API를 사용해볼것 RestTemplate를 스프링 빈으로 등록 package com.mkl.book.Configuration; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Confi..
tmdrl5779.tistory.com
그래서 전체 책은 아니지만 베스트 셀러 정보를 가진 인터파크의 도서 베스트셀러 API를 사용하였다.
사용 예시
@Service
public class BookApiClient {
private final RestTemplate restTemplate;
@Autowired
public BookApiClient(RestTemplate restTemplate) {
this.restTemplate = restTemplate;
}
private final String OpenBookUrl_getBooks = "http://book.interpark.com/api/bestSeller.api?key="+키값+"&categoryId=100&output=json";
public BooksResponseDto requestBook(){
final HttpHeaders headers = new HttpHeaders();
final HttpEntity<?> entity = new HttpEntity<>(headers);
BooksResponseDto body = restTemplate.exchange(OpenBookUrl_getBooks, HttpMethod.GET, entity, BooksResponseDto.class).getBody();
return body;
}
}
실행 결과
org.springframework.web.client.UnknownContentTypeException: Could not extract response: no suitable HttpMessageConverter found for response type [class com.mkl.book.booktest.DTO.BooksResponseDto] and content type [text/json;charset=utf-8]
???
네이버 API사용할 떄와 똑같이 했는데 에러가 났다...
Spring을 처음 써보는 것이라서 무슨에러인지 뭐 때문에 에러가 난건지 한참을 찾았다....ㄷ
찾아본결과 내가 정의한 class와 json을 맵핑하려면 http헤더의 content-type이 application/json이여야 하는것 같다.
application/json은 공식 MIME타입이라고 한다..
근데 내가 요청한 API의 헤더 타입을 살펴본결과 Text/json이었다... 이걸 몰라서 시간날림
그래서 해결 방법은 요청을 받고 해당 헤더의 content-type을 바꿔줘야 했다.
헤더를 설정해줄수 있는 메소드가 있었다.
headers.setContentType(MediaType.APPLICATION_JSON);
추가해서 실행했는데 똑같이 에러가 나왔다...
계속해서 찾아본결과.
@Service
public class BookApiClient {
private final RestTemplate restTemplate;
private final BookRepository bookRepository;
@Autowired
public BookApiClient(RestTemplate restTemplate, BookRepository bookRepository) {
this.restTemplate = restTemplate;
this.bookRepository = bookRepository;
}
private final String OpenBookUrl_getBooks = "http://book.interpark.com/api/bestSeller.api?key=키값&categoryId=100&output=json";
public BooksResponseDto requestBook(){
restTemplate.getInterceptors().add((request, body, execution) -> {
ClientHttpResponse response = execution.execute(request,body);
response.getHeaders().setContentType(MediaType.APPLICATION_JSON);
return response;
});
final HttpHeaders headers = new HttpHeaders();
final HttpEntity<?> entity = new HttpEntity<>(headers);
BooksResponseDto body = restTemplate.exchange(OpenBookUrl_getBooks, HttpMethod.GET, entity, BooksResponseDto.class).getBody();
return body;
}
이런식으로 하면 에러가 해결됐다..
강제적으로 헤더의 타입을 바꾸는것이다.
동작방식은 잘 모르겠다...
'Programming > Spring' 카테고리의 다른 글
[Spring] CSRF, XSS (0) | 2021.02.11 |
---|---|
[Spring] 커맨드 객체, @ModelAttribute (0) | 2021.02.07 |
[Spring] @Controller @Service @Repository (0) | 2021.01.29 |
[Spring] 네이버 검색 API 사용 (0) | 2021.01.25 |
[Spring] @RequestParam, @PathVariable (0) | 2021.01.25 |