远程调用--webClient

前言

非阻塞、响应式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

//        创建webClient
        WebClient 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;
    }
}

  • 5
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值