All Day Tired

스프링에서 RestTemplate 예제 본문

Back/Spring

스프링에서 RestTemplate 예제

yu.dev 2024. 8. 20. 16:21

개발하다보니까 RestTemplate로 API를 호출하는게 생김

혹시라도 나중에 코드 찾을까봐 일단 써놓음

(근데 더 모던한 RestClient가 있대 Spring 6버전부터)

 

import org.codehaus.jackson.map.ObjectMapper;
import org.json.JSONObject;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;
import org.springframework.util.UriComponentsBuilder;



    Map<String, Obejct> body = new HashMap<>();
    body.put("파라미터명", 파라미터값);	//파라미터가 여러개라면 여러개 put 하면 됨
    
    HttpEntity httpEntity = new HttpEntity(body);
    RestTemplate restTemplate = new RestTemplate();
    UriComponentsBuilder uriBuilder = UriComponentsBuilder.fromHttpUrl("api주소");	//ex:http://00.00.00.00:8000/ex 이런식의 주소
    ResponseEntity resultEntity = restTemplate.exchange(uriBuilder.toUriString(), HttpMethod.POST, httpEntity, String.class);	//get이면 HttpMethod.POST -> HttpMethod.Get으로 해주면 됨
    
    String resultStr = (String) resultEntity.getBody();
    
    //아래는 json으로 변환시키는 코드로 참고용
    //단, 오는 결과 형식이 JSON형식이여야 함
    ObjectMapper mapper = new ObjectMapper();
    JSONObject jsonObject = mapper.readValue(resultStr, JSONObject.class);
//  Map<String, Object> map = mapper.readValue(resultStr, HashMap.class); 이렇게 쓰면 Map으로 받을 수 있음, 이것도 형식이 Map형식이여야 함
Comments