HTTP Interface
-
Spring 允许我们通过定义接口的方式,给任意位置发送 http 请求,实现远程调用,可以用来简化 HTTP 远程访问。需要webflux场景才可
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-webflux</artifactId> </dependency>
-
定义接口
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上不一样. }
-
创建代理&测试
@SpringBootTest class Boot05TaskApplicationTests { @Test public 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; } }
-
生产模式----编写配置类config/WeatherConfiguration,@config文章来源:https://www.toymoban.com/news/detail-604458.html
@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; }
-
WeatherService文章来源地址https://www.toymoban.com/news/detail-604458.html
@Autowired WeatherInterface WeatherInterface //4、测试调用 Mono<String> weather = WeatherInterface.search(city,"APPCODE XXXXXXXX"); return weather;
到了这里,关于WebClient,HTTP Interface远程调用阿里云API的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!