[TIL]Spring RestTemplate

Funnystyle·2021년 3월 9일
0

Spring Framework 에서 server-to-server GET/POST Request 를 보내고 싶을 때, RestTemplate 를 사용할 수 있다.
XXXForObejct 를 쓰면 json 응답을 Map 으로 받을 수 있고, POST 요청시 파라메터들은 MultiValueMap 으로 보낼 수 있다.

GET Method

@Test
public void test_getForObject() {
   Map<String, String> result = restTemplate.getForObject(URL, HashMap.class);
   log.info("result: {}", result);
}

POST Method

@Test
public void test_postForObject() {
   MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
   params.add("param1", "value1");
   params.add("param2", "value2");
 
   Map<String, String> result = restTemplate.postForObject(URL, Employee.class, params);
   log.info("result: {}", result);
}

Timeout

private RestTemplate getRestTemplate() {
    HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory();
    factory.setConnectTimeout(10*1000);
    factory.setReadTimeout(10*1000);
    RestTemplate restTemplate = new RestTemplate(factory);
    return restTemplate;
}

출처:
https://advenoh.tistory.com/46
https://m.blog.naver.com/mk1126sj/221032571275
https://hspmuse.tistory.com/entry/Spring-RestTemplate-timeout-%EC%84%A4%EC%A0%95

profile
polyglot

0개의 댓글