Spring
Spring REST API 예제
husks
2023. 3. 8. 11:33
반응형
Spring에서는 RestTemplate 클래스를 사용하여 JSON 응답을 반환하고 JSON 요청을 보내는 API를 호출할 수 있습니다.
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;
import java.util.HashMap;
import java.util.Map;
public class ApiClient {
public static void main(String[] args) {
// RestTemplate 객체 생성
RestTemplate restTemplate = new RestTemplate();
// 요청 페이로드를 Map 개체로 정의
Map<String, String> payload = new HashMap<>();
payload.put("key1", "value1");
payload.put("key2", "value2");
// JSON 데이터를 보내고 있음을 나타내도록 요청의 헤더를 설정합니다.
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
// 페이로드 및 헤더를 사용하여 요청 엔터티 만들기
HttpEntity<Map<String, String>> requestEntity = new HttpEntity<>(payload, headers);
// POST 요청을 API에 보내고 응답 받기
ResponseEntity<String> responseEntity = restTemplate.postForEntity(
"https://example.com/api/data",
requestEntity,
String.class);
// 응답 본문을 문자열로 가져오기
String responseBody = responseEntity.getBody();
// 응답 본문 출력
System.out.println(responseBody);
}
}
이 예제에서는 RestTemplate 클래스를 사용하여 URL 'https://example.com/api/data'에 대한 POST 요청의 JSON 페이로드를 보냅니다. postForEntity 메서드는 요청을 보내고 응답을 받는 데 사용되며 세 가지 매개 변수를 사용합니다.
- 요청을 보낼 URL
- 페이로드 및 헤더를 포함하는 요청 엔터티
- 예상 응답 유형의 클래스(이 경우 String.class)
또한 Content-Type 헤더를 application/json으로 설정하여 요청에서 JSON 데이터를 보내고 있음을 나타냅니다.
응답 본문이 문자열로 있으면 프로그램에서 필요에 따라 조작하고 사용할 수 있습니다.
반응형