| 일 | 월 | 화 | 수 | 목 | 금 | 토 |
|---|---|---|---|---|---|---|
| 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 |
Tags
- 백준
- jface
- Git
- 후기
- 맛집
- kibana
- javascript
- effective
- 리뷰
- 이펙티브
- nodejs
- elasticsearch
- boot
- Spring Boot
- MySQL
- node
- Spring
- java
- 알고리즘
- java8
- Web
- 인터페이스
- RCP
- 독후감
- JPA
- 스프링
- 자바스크립트
- 엘라스틱서치
- error
- 자바
Archives
- Today
- Total
wedul
Spring에서 url 요청하는 RestTemplate 설명 본문
반응형
Spring 기반 프로젝트 진행 시 URL을 요청할 때가 있다.
이를 Apache의 HttpClient 라이브로리를 사용하여 할 수 있지만, 스프링 프로젝트에서는 SpringTemplate를 사용하여 쉽게 요청할 수 있다. (httpClient와 RestTemplate의 차이는 하단의 링크참조)
사용법은 아주 간단하다. 각 요청 Method 마다 하단의 메소드를 이용하여 호출하기만 하면된다.
1. Get
1 2 3 4 5 | RestTemplate restTemplate = new RestTemplate(); String fooResourceUrl = "http://localhost:8080/spring-rest/foos"; ResponseEntity<String> response = restTemplate.getForEntity(fooResourceUrl + "/1", String.class); | cs |
2. Post
1 2 3 4 5 6 | ClientHttpRequestFactory requestFactory = getClientHttpRequestFactory(); RestTemplate restTemplate = new RestTemplate(requestFactory); HttpEntity<Foo> request = new HttpEntity<>(new Foo("bar")); Foo foo = restTemplate.postForObject(fooResourceUrl, request, Foo.class); | cs |
PUT과 DELETE는 하단 참조페이지에서 확인가능하다.
또한 이런 RestTemplate 기능에서 비동기로 결과값을 받을 수 있는 라이브러리가 추가되었다.
Spring 4에 추가된 AsyncRestTemplate를 이용하면 url을 요청하고 비동기로 결과를 받을 수 있다.
사용법은 다음과 같다.
1 | ListenableFuture<ResponseEntity<Map>> entity = asyncRestTemplate.getForEntity("https://httpbin.org/get", Map.class); | cs |
각 사례별 자세한 설명 (httpClient와 비교)
https://vnthf.github.io/blog/Java-RestTemplate%EC%97%90-%EA%B4%80%ED%95%98%EC%97%AC/
Spring API 문서
https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/client/RestTemplate.html
자세한 사용법
http://www.baeldung.com/rest-template
반응형
'web > Spring' 카테고리의 다른 글
| Spring boot에서 Spring security를 사용하여 로그인 하기 (12) | 2018.05.27 |
|---|---|
| spring boot에 https 접속 적용하기 (0) | 2018.05.27 |
| spring boot에서 jsp사용하기 (0) | 2018.05.27 |
| spring boot 재시작 없이 frontend(html, js..) 변경내용 사용하기 (1) | 2018.05.27 |
| Tomcat에서 war 사이에 session 공유 (0) | 2018.05.27 |