远程调用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;}
}