看了下spring webflux的知识点,随便写了个小工具去解析youtube上的视频地址,然后就有了设置代理和ssl部分的实践,记录一下
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
</dependency>
一 . webclient设置SSL
SslContext sslContext = SslContextBuilder
.forClient()
.trustManager(InsecureTrustManagerFactory.INSTANCE)
.build();
ReactorClientHttpConnector connector = new ReactorClientHttpConnector(options -> options.sslContext(sslContext)) ;
WebClient client = WebClient.builder().clientConnector(connector)
.baseUrl("https://www.youtube.com")
.build();
二 . webclient设置代理
SslContext sslContext = SslContextBuilder
.forClient()
.trustManager(InsecureTrustManagerFactory.INSTANCE)
.build();
ReactorClientHttpConnector connector = new ReactorClientHttpConnector(options -> options
.httpProxy(addressSpec -> addressSpec
.address(new InetSocketAddress("127.0.0.1", 1080)))
);
WebClient client = WebClient.builder().clientConnector(connector)
.baseUrl("https://www.youtube.com")
.build();
三 . get请求
// 比如访问 http://www.xxx.com/playlist?param=xxxx
WebClient client = WebClient.builder()
.baseUrl("http://www.xxx.com")
.build();
WebClient.ResponseSpec responseSpec = client
.get()
.uri(uriBuilder -> uriBuilder
.path("playlist") // 子路径
.queryParam("param", "xxxx") // 参数
.build())
.acceptCharset(StandardCharsets.UTF_8)
.accept(MediaType.ALL)
.retrieve();
// 返回Mono还是Flux 要根据接口实际情况调整
Mono<String> objectMono = responseSpec.bodyToMono(String.class);
// Flux<String> objectFlux = responseSpec.bodyToFlux(String.class);
四 . post请求(form表单参数)
// 比如访问 http://www.xxx.com/postReq , 用form表单方式传参
WebClient client = WebClient.builder()
.baseUrl("http://www.xxx.com")
.build();
WebClient.ResponseSpec responseSpec = client
.post()
.uri("postReq")
.body(BodyInserters.fromFormData("mediaurl", url)) // form表单参数,可以增加多个参数
.retrieve();
Mono<String> objectMono = responseSpec.bodyToMono(String.class);
五 . 通过URL对象获取请求信息
String url = "http://www.xxx.com/getReq?param=abc¶m2=cde" ;
URL finalCheckUrl = new URL(url);
WebClient.ResponseSpec retrieve = client.get()
.uri(uriBuilder -> uriBuilder
.scheme(finalCheckUrl.getProtocol())
.host(finalCheckUrl.getHost())
.path(finalCheckUrl.getPath())
.query(finalCheckUrl.getQuery())
.build())
.retrieve();
注意: 如果请求的地址都是同一个host, 把webclient 抽取出来,不要每次请求都去新建webclient .
强烈推荐以下文章,作为入门知识
- Spring Reactor 入门与实践 会讲解webflux的一些概念
- spring 5 webclient使用指南 webclient 的常见使用