๐ ์๋น์ค๋จ์ ์์ฑํ์ฌ ์ฌ์ฉ
public class MyService {
private final WebClient webClient;
public MyService(WebClient.Builder webClientBuilder) {
this.webClient = webClientBuilder.baseUrl("https://test.example.com").build();
}
// get ์์ฒญ
public Mono<String> fetchData() {
return webClient.get()
.uri("/data")
.retrieve()
.bodyToMono(String.class);
}
// post ์์ฒญ
public Mono<String> sendData(String data) {
return webClient.post()
.uri("/endpoint")
.header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
.body(BodyInserters.fromValue(data))
.retrieve()
.bodyToMono(String.class);
}
}
- WebClient.Builder๋ฅผ ์ฌ์ฉํ์ฌ baseUrl ์ค์
- Mono<String>์ ๋ฐํํ์ฌ ๋น๋๊ธฐ ์ฒ๋ฆฌ ๊ฐ๋ฅ
- GET ๋ฐ POST ๋ฉ์๋ ๋ชจ๋ ์ฌ์ฉ ๊ฐ๋ฅ
๐ ์ปจํธ๋กค๋ฌ์์ ์ง์ ์ฌ์ฉ - post
public class Contoller {
public Map<String, Object> fetchData(String uri, Map<String, Object> params) {
String url = "https://test.example.com";
MultiValueMap<String, String> formData = new LinkedMultiValueMap<>();
try {
for(Map.Entry<String, Object> entry: params.entrySet()) {
String key = entry.getKey();
String value = entry.getValue().toString();
formData.add(key, value);
}
WebClient webClient = WebClient.create(uri);
// ์์ฒญ ๋น๋
Mono<String> response = webClient
.method(HttpMethod.POST)
.uri(uri)
.contentType(MediaType.APPLICATION_FORM_URLENCODED)
.body(BodyInserters.fromFormData(formData))
.retrive()
.bodyToMono(String.class);
String responseBody = response.block();
ObjectMapper objectMapper = new ObjectMapper();
Map<String, Object> result = objectMapper.readValue(responseBody, new TypeReference<Map<String, Object>>() {})
return result;
} catch (Exception e) {
LOGGER.error("์๋ฌ๋ก๊ทธ ์ถ๋ ฅ = ", e);
throw new Exception(); // ์ต์
์
}
}
}
- WebClient.create()๋ฅผ ์ฌ์ฉํ์ฌ ๊ฐ๋จํ๊ฒ ์ธ์คํด์ค ์์ฑ
- BodyInserters.fromFormData()๋ก Form ๋ฐ์ดํฐ ์ ์ก
- ObjectMapper๋ฅผ ์ฌ์ฉํด **์๋ต(JSON)**์ Map<String, Object>๋ก ๋ณํ
'๋ฐฑ์๋ > Spring Boot' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[Spring Boot] ConflictingBeanDefinitionException ์ค๋ฅ ํด๊ฒฐ ๋ฐฉ๋ฒ (0) | 2024.02.13 |
---|---|
[Spring Boot] ๋ฉ์ผ ๋ฐ์ก (0) | 2023.07.28 |
[Spring Boot] java.net.UnkownHostException ์๋ฒ์์ ์ธ๋ถ API ํธ์ถ ์ ์๋ฌ (0) | 2023.07.26 |
[Spring Boot] ์๋ฒ Class ํ์ผ ์์ ํ์ฌ ๋ฐ๋ก ์๋ฒ์ ์ ๋ก๋ํ๊ธฐ (0) | 2023.07.19 |
[Spring Boot] VSCode์์ jar ํ์ผ ์ถ๊ฐํ๊ธฐ (0) | 2023.07.03 |