업무중필요모음/Snippet

[JAVA] - RestTemplete

도원결의 2024. 8. 12. 10:33


RestTemplete이란 ?

* Spring에서 지원하는 객체로 간편하게 Rest 방식 API를 호출할 수 있는 Spring(Spring 3 ↑) 내장 클래스



`RestTemplete`을 이용한 Json 파싱 예제

 

1) 의존성 추가

<dependency>
    <groupId>org.apache.httpcomponents.client5</groupId>
    <artifactId>httpclient5</artifactId>
</dependency>
<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-web</artifactId>
</dependency>


2) 객체 생성

@JsonIgnoreProperties(ignoreUnknown = true)
@Data
public class WorldTime {

    @JsonProperty("datetime")
    @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ss.SSSSSSXXX")
    private LocalDateTime dateTime;

    private String abbreviation;
    private String clientIp;
    private Integer dayOfWeek;
    private Integer dayOfYear;
    private Boolean dst;
    private String dstFrom;
    private Integer dstOffset;
    private String dstUntil;
    private Integer rawOffset;
    private String timezone;

    @JsonIgnore
    private Long unixtime;
    @JsonIgnore
    private String utcDatetime;
    @JsonIgnore
    private String utcOffset;
    @JsonIgnore
    private Integer weekNumber;
}

 

3) API 호출

@RequiredArgsConstructor
public class EmsBatchResultServiceImpl implements EmsBatchResultService {
    //RestTemplate 객체 생성
    private final RestTemplate restTemplate;

    private WorldTime getWorldTime() {
        String url = "http://worldtimeapi.org/api/timezone/Asia/Seoul"; 
        //WorldTime 타입으로 변환
        return restTemplate.getForObject(url, WorldTime.class); 
    }


4) 결과

INFO: Response: WorldTime(dateTime=2024-01-18T11:44:25.011235+09:00, 

abbreviation=KST, clientIp=106.251.230.10, dayOfWeek=4, dayOfYear=18, dst=false, 

dstFrom=null, dstOffset=0, dstUntil=null, rawOffset=32400, timezone=Asia/Seoul)