看了下spring webflux的知識點颁独,隨便寫了個小工具去解析youtube上的視頻地址,然后就有了設(shè)置代理和ssl部分的實踐吨枉,記錄一下
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
</dependency>
一 . webclient設(shè)置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設(shè)置代理
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") // 參數(shù)
.build())
.acceptCharset(StandardCharsets.UTF_8)
.accept(MediaType.ALL)
.retrieve();
// 返回Mono還是Flux 要根據(jù)接口實際情況調(diào)整
Mono<String> objectMono = responseSpec.bodyToMono(String.class);
// Flux<String> objectFlux = responseSpec.bodyToFlux(String.class);
四 . post請求(form表單參數(shù))
// 比如訪問 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表單參數(shù)蹦渣,可以增加多個參數(shù)
.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 的常見使用