之前写了一篇restTemplate使用实例,由于spring 5全面引入reactive,同时也有了restTemplate的reactive版webclient,本文就来对应展示下webclient的基本使用。
请求携带header
携带cookie
@Test public void testWithCookie(){ Mono<String> resp = WebClient.create() .method(HttpMethod.GET) .uri("http://baidu.com") .cookie("token","xxxx") .cookie("JSESSIONID","XXXX") .retrieve() .bodyToMono(String.class); LOGGER.info("result:{}",resp.block()); }
携带basic auth
@Test public void testWithBasicAuth(){ String basicAuth = "Basic "+ Base64.getEncoder().encodeToString("user:pwd".getBytes(StandardCharsets.UTF_8)); LOGGER.info(basicAuth); Mono<String> resp = WebClient.create() .get() .uri("http://baidu.com") .header(HttpHeaders.AUTHORIZATION,basicAuth) .retrieve() .bodyToMono(String.class); LOGGER.info("result:{}",resp.block()); }
设置全局user-agent
@Test public void testWithHeaderFilter(){ WebClient webClient = WebClient.builder() .defaultHeader(HttpHeaders.USER_AGENT, "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36") .filter(ExchangeFilterFunctions .basicAuthentication("user","password")) .filter((clientRequest, next) -> { LOGGER.info("Request: {} {}", clientRequest.method(), clientRequest.url()); clientRequest.headers() .forEach((name, values) -> values.forEach(value -> LOGGER.info("{}={}", name, value))); return next.exchange(clientRequest); }) .build(); Mono<String> resp = webClient.get() .uri("https://baidu.com") .retrieve() .bodyToMono(String.class); LOGGER.info("result:{}",resp.block()); }
get请求
使用placeholder传递参数
@Test public void testUrlPlaceholder(){ Mono<String> resp = WebClient.create() .get() //多个参数也可以直接放到map中,参数名与placeholder对应上即可 .uri("http://") .defaultHeader(HttpHeaders.CONTENT_TYPE, "application/vnd.github.v3+json") .defaultHeader(HttpHeaders.USER_AGENT, "Spring 5 WebClient") .build(); WebClient.ResponseSpec responseSpec = webClient.method(HttpMethod.GET) .uri("/user/repos?sort={sortField}&direction={sortDirection}", "updated", "desc") .retrieve(); Mono<String> mono = responseSpec .onStatus(e -> e.is4xxClientError(),resp -> { LOGGER.error("error:{},msg:{}",resp.statusCode().value(),resp.statusCode().getReasonPhrase()); return Mono.error(new RuntimeException(resp.statusCode().value() + " : " + resp.statusCode().getReasonPhrase())); }) .bodyToMono(String.class) .doOnError(WebClientResponseException.class, err -> { LOGGER.info("ERROR status:{},msg:{}",err.getRawStatusCode(),err.getResponseBodyAsString()); throw new RuntimeException(err.getMessage()); }) .onErrorReturn("fallback"); String result = mono.block(); LOGGER.info("result:{}",result); }
可以使用onStatus根据status code进行异常适配可以使用doOnError异常适配可以使用onErrorReturn返回默认值小结
webclient是新一代的async rest template,api也相对简洁,而且是reactive的,非常值得使用。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。