API 호출은 보통 클라이언트에서 일어나게 되어 프론트단에서 진행되지만 프로젝트를 진행하다 보면 백엔드 서버에서 다른 서버로 API를 호출해야 하는 경우가 생깁니다. 이러한 경우 Spring Boot에서는 HTTP 통신을 간단하게 사용할 수 있는 RestTemplate를 제공하고 있습니다.
RestTemplate는 Spring에서 제공하는 HTTP 클라이언트로, 다양한 HTTP 메서드(GET, POST, PUT, DELETE 등)를 사용하여 원격 서버와 통신할 수 있습니다. 간단한 설정으로 RESTful 웹 서비스와의 통신을 처리할 수 있으며, 주로 외부 API와의 통합이나 마이크로서비스 간의 통신에 활용됩니다.
RestTemplate를 사용하여 HTTP 요청을 보내는 방법으로는 getForEntity, postForEntity, exchange가 있습니다. 이름 그대로 Get 요청, Post 요청, 이외의 다른 요청들은 exchange를 사용하게 됩니다.
먼저 Get 요청부터 알아보겠습니다.
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
@Service
public class MyService {
private final RestTemplate restTemplate;
public MyService(@Autowired RestTemplate restTemplate) {
this.restTemplate = restTemplate;
}
public void getRequest() {
// 요청을 보낼 URL
String apiUrl = "https://api.example.com/data";
// HTTP GET 요청 보내기
ResponseEntity<String> responseEntity = restTemplate.getForEntity(apiUrl, String.class);
// 응답 값
String responseBody = responseEntity.getBody();
System.out.println("GET Response: " + responseBody);
}
}
Get 요청은 restTemplate 클래스에 있는 getForEntity 메소드로 진행할 수 있습니다.
파라미터로 요청을 보낼 URL와 response의 DataType을 지정해주면 됩니다.
요청에 성공하면 responseEntity에 담기게 되며 getBody를 통해 body 값을 가져올 수 있습니다.
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
@Service
public class MyService {
private final RestTemplate restTemplate;
public MyService(@Autowired RestTemplate restTemplate) {
this.restTemplate = restTemplate;
}
public void fetchPostRequest() {
// 요청을 보낼 URL
String apiUrl = "https://api.example.com/data";
// HTTP 헤더 설정
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
// 요청 데이터 생성
MultiValueMap<String, String> requestData = new LinkedMultiValueMap<>();
parameters.add("key", "value");
// HTTP POST 요청 보내기
ResponseEntity<String> responseEntity = restTemplate.postForEntity(apiUrl, requestEntity, String.class);
// 응답 값
String responseBody = responseEntity.getBody();
System.out.println("POST Response: " + responseBody);
}
}
Post 요청은 restTemplate 클래스에 있는 postForEntity 메소드로 진행할 수 있습니다.
파라미터로 요청을 보낼 URL와 resquestData, response의 DataType을 지정해주면 됩니다.
요청에 성공하면 responseEntity에 담기게 되며 getBody를 통해 body 값을 가져올 수 있습니다.
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
@Service
public class MyService {
private final RestTemplate restTemplate;
public MyService(@Autowired RestTemplate restTemplate) {
this.restTemplate = restTemplate;
}
public void fetchExchangeRequest() {
// 요청을 보낼 URL
String apiUrl = "https://api.example.com/data";
// HTTP GET 요청 보내기
ResponseEntity<String> responseEntity = restTemplate.exchange(
apiUrl,
HttpMethod.GET,
null,
String.class
);
// 응답 값
String responseBody = responseEntity.getBody();
System.out.println("Exchange GET Response: " + responseBody);
}
}
exchange를 통해 Get 요청을 보내는 예시입니다.
exchage의 파라미터로는 Url, HttpMethod, request body, 반환 값 DataType이 있습니다.
해당 코드에서는 Get 요청이므로 request body는 null이고 HttpMethod.GET으로 보냅니다.
다른 메소드들도 마찬가지로 HttpMethod.POST, HttpMethod.PUT 등으로 지정해주면 원하는 요청을 보낼 수 있습니다.