본문 바로가기
Spring

[spring boot] springboot에서 다른 서버로 axios 요청 보내기

by whitedeveloper 2023. 3. 31.

Spring Boot에서도 다른 서버로 Axios 요청을 보낼 수 있습니다.

이를 위해서는 RestTemplate 또는 WebClient를 사용하여 요청을 보내면 됩니다.

RestTemplate는 Spring 프레임워크에서 제공하는 HTTP 요청 및 응답을 다루는 간단한 API이며, WebClient는 Java 8에서 추가된 리액티브 프로그래밍을 지원하는 비동기 HTTP 클라이언트입니다.

두 가지 방법 모두 사용 가능하지만,

최신의 추세에 따라 WebClient를 사용하는 것이 권장됩니다.

아래는 WebClient를 사용하여 다른 서버로 Axios 요청을 보내는 예시입니다.

import org.springframework.stereotype.Service;

import org.springframework.web.reactive.function.client.WebClient;

import reactor.core.publisher.Mono;

@Service

public class MyService { private final WebClient webClient;

      public MyService(WebClient.Builder webClientBuilder) {

            this.webClient = webClientBuilder.build();

      }

      public Mono getRemoteData() {

            return webClient.get() .uri("http://example.com/data") .retrieve() .bodyToMono(String.class);

      }

}

이 예제에서 WebClient는 MyService 클래스에서 생성되며, getRemoteData() 메소드에서 http://example.com/data 로 HTTP GET 요청을 보냅니다.

이 요청의 결과로 Mono 객체를 반환합니다.

Mono는 Reactive Stream의 Publisher 인터페이스를 구현한 리액티브 타입 중 하나입니다.

이와 유사한 방법으로 RestTemplate을 사용하여 HTTP 요청을 보낼 수 있습니다.

'Spring' 카테고리의 다른 글

[Spring]API 작성하기 - DELETE API  (0) 2023.01.15
[Spring]PUT API  (0) 2023.01.15
[Spring]API작성하기 - POST API  (0) 2023.01.14
[Spring] API작성하기 - GET  (0) 2023.01.08
[Spring] Talend API Tester  (0) 2023.01.08