遠程調用webClient
- 前言
- 1、創建webClient
- 2、準備數據
- 3、執行請求
- 4、接收返回響應到的數據
- 整體代碼
前言
非阻塞、響應式HTTP客戶端
1、創建webClient
WebClient client = WebClient.create();
2、準備數據
Map<String,String> params = new HashMap<>();params.put("area","西安");
3、執行請求
Mono<String> mono = client.get().uri("要請求的接口").accept(MediaType.APPLICATION_JSON) //定義響應的內容類型,以json格式趕回.header("Authorization","APPCODE 93b7e19861a24c519a7548b17dc46d75").retrieve().bodyToMono(String.class)return mono;}
4、接收返回響應到的數據
@GetMapping("/weather")public Mono<String> weather(@RequestParam("city") String city){
// 查詢天氣Mono<String> weather = weatherService.weather(city);return weather;}
整體代碼
package com.atguigu.boot305ssm.service;import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Mono;import java.util.HashMap;
import java.util.Map;/*** @author jitwxs* @date 2024年03月03日 10:15*/
@Service
public class WeatherService {public Mono<String> weather(String city){
// 遠程調用api// 創建webClientWebClient client = WebClient.create();// 準備數據Map<String,String> params = new HashMap<>();params.put("area","西安");// 定義發送請求行為Mono<String> mono = client.get().uri("要請求的接口").accept(MediaType.APPLICATION_JSON) //定義響應的內容類型,以json格式趕回.header("Authorization","APPCODE 93b7e19861a24c519a7548b17dc46d75").retrieve().bodyToMono(String.class)return mono;}
}