当前位置: 首页 > news >正文

WebClient,HTTP Interface远程调用阿里云API

 HTTP Interface

  1. Spring 允许我们通过定义接口的方式,给任意位置发送 http 请求,实现远程调用,可以用来简化 HTTP 远程访问。需要webflux场景才可

    <dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-webflux</artifactId>
    </dependency>
  2. 定义接口

    public interface BingService {@GetExchange(url = "/search",accept="application/json")//请求的地址,接收json数据Mono<String> search(@RequestParam("area") String keyword,@RequsetHeader("Authorization") String auth);//在service里@GetExchange表示我要发一个请求参数叫"area"
    //和controller上不一样.
    }
  3. 创建代理&测试

    @SpringBootTest
    class Boot05TaskApplicationTests {@Testpublic Mono<String> weather(String city) {//1、创建客户端WebClient client = WebClient.builder().baseUrl("https://cn.bing.com")//给哪发请求.codecs(clientCodecConfigurer -> {clientCodecConfigurer.defaultCodecs().maxInMemorySize(256*1024*1024);//响应数据量太大有可能会超出BufferSize,所以这里设置的大一点}).build();//2、创建工厂HttpServiceProxyFactory factory = HttpServiceProxyFactory.builder(WebClientAdapter.forClient(client)).build();//3、获取代理对象BingService bingService = factory.createClient(BingService.class);//BingService.class接口名//4、测试调用Mono<String> search = bingService.search(city,"APPCODE XXXXXXXX");return weather;}}

  4. 生产模式----编写配置类config/WeatherConfiguration,@config

    @Bean
    WeatherInterface WeatherInterface(){
    //1、创建客户端WebClient client = WebClient.builder().baseUrl("https://cn.bing.com")//给哪发请求.codecs(clientCodecConfigurer -> {clientCodecConfigurer.defaultCodecs().maxInMemorySize(256*1024*1024);//响应数据量太大有可能会超出BufferSize,所以这里设置的大一点}).build();//2、创建工厂HttpServiceProxyFactory factory = HttpServiceProxyFactory.builder(WebClientAdapter.forClient(client)).build();//3、获取代理对象WeatherInterface WeatherInterface = factory.createClient(WeatherInterface.class);//BingService.class接口名
    return WeatherInterface;
    }
  5. WeatherService

    @Autowired
    WeatherInterface WeatherInterface//4、测试调用Mono<String> weather = WeatherInterface.search(city,"APPCODE XXXXXXXX");return weather;
    

http://www.lryc.cn/news/95721.html

相关文章:

  • 飞书ChatGPT机器人 – 打造智能问答助手实现无障碍交流
  • React、Vue框架如何实现组件更新,原理是什么?
  • 常见面试题之设计模式--策略模式
  • redis多key问题
  • kafka第三课-可视化工具、生产环境问题总结以及性能优化
  • 2_Apollo4BlueLite中断控制器NVIC
  • WAIC2023:图像内容安全黑科技助力可信AI发展
  • 微信小程序quickstartFunctions中云函数的应用
  • Go学习 2、程序结构
  • SpringBoot整合JavaMail
  • Spring6——入门
  • 【计算机视觉 | 目标检测 | 图像分割】arxiv 计算机视觉关于目标检测和图像分割的学术速递(7 月 17 日论文合集)
  • 为什么需要GP(Global Platform)认证?
  • eclipse 格式化代码 快捷键
  • 深入探索Socks5代理与网络安全
  • 【NLP】如何使用Hugging-Face-Pipelines?
  • 网络安全(黑客)自学笔记
  • spring数据校验
  • 因材施教,有道发布“子曰”教育大模型,落地虚拟人口语教练等六大应用
  • golang waitgroup
  • 单列模式多学两遍
  • Spring Cloud【SkyWalking网络钩子Webhooks、SkyWalking钉钉告警、SkyWalking邮件告警】(十六)
  • 【力扣每日一题】2023.7.25 将数组和减半的最少操作次数
  • Docker-Compose 轻松搭建 Grafana+InfluxDb 实用 Jmeter 监控面板
  • 异构线程池的c++实现方案
  • Python实现抽象工厂模式
  • @vue/cli安装
  • 用友全版本任意文件上传漏洞复现
  • 程序员面试系列,MySQL常见面试题?
  • 前端Web实战:从零打造一个类Visio的流程图拓扑图绘图工具