sequence
Since Spring 5 has fully introduced Reactive, and the Reactive version of WebClient of restTemplate is available, this article will show the basic use of WebClient.
Request to carry header
- Carry a 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());
}
Copy the code
- With 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());
}
Copy the code
- Set the global 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());
}
Copy the code
A get request
- Placeholder for passing parameters
@Test
public void testUrlPlaceholder(){Mono<String> resp = webClient.create ().get();"http://www.baidu.com/s?wd={key}&other={another}".Weather in Beijing."test"Retrieve ().bodytomono (string.class); LOGGER.info("result:{}",resp.block());
}
Copy the code
- Pass parameters using uriBuilder
@Test
public void testUrlBiulder(){
Mono<String> resp = WebClient.create()
.get()
.uri(uriBuilder -> uriBuilder
.scheme("http")
.host("www.baidu.com")
.path("/s")
.queryParam("wd".Weather in Beijing)
.queryParam("other"."test")
.build())
.retrieve()
.bodyToMono(String.class);
LOGGER.info("result:{}",resp.block());
}
Copy the code
Post form
@Test
public void testFormParam(){
MultiValueMap<String, String> formData = new LinkedMultiValueMap<>();
formData.add("name1"."value1");
formData.add("name2"."value2");
Mono<String> resp = WebClient.create().post()
.uri("http://www.w3school.com.cn/test/demo_form.asp")
.contentType(MediaType.APPLICATION_FORM_URLENCODED)
.body(BodyInserters.fromFormData(formData))
.retrieve().bodyToMono(String.class);
LOGGER.info("result:{}",resp.block());
}
Copy the code
post json
- Use beans to post
static class Book {
String name;
String title;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
}
@Test
public void testPostJson(){
Book book = new Book();
book.setName("name");
book.setTitle("this is title");
Mono<String> resp = WebClient.create().post()
.uri("http://localhost:8080/demo/json")
.contentType(MediaType.APPLICATION_JSON_UTF8)
.body(Mono.just(book),Book.class)
.retrieve().bodyToMono(String.class);
LOGGER.info("result:{}",resp.block());
}
Copy the code
- Post raw JSON
@Test
public void testPostRawJson(){
Mono<String> resp = WebClient.create().post()
.uri("http://localhost:8080/demo/json")
.contentType(MediaType.APPLICATION_JSON_UTF8)
.body(BodyInserters.fromObject("{\n" +
" \"title\" : \"this is title\",\n" +
" \"author\" : \"this is author\"\n" +
"}"))
.retrieve().bodyToMono(String.class);
LOGGER.info("result:{}",resp.block());
}
Copy the code
Post binary — Upload a file
@Test
public void testUploadFile(){
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.IMAGE_PNG);
HttpEntity<ClassPathResource> entity = new HttpEntity<>(new ClassPathResource("parallel.png"), headers);
MultiValueMap<String, Object> parts = new LinkedMultiValueMap<>();
parts.add("file", entity);
Mono<String> resp = WebClient.create().post()
.uri("http://localhost:8080/upload")
.contentType(MediaType.MULTIPART_FORM_DATA)
.body(BodyInserters.fromMultipartData(parts))
.retrieve().bodyToMono(String.class);
LOGGER.info("result:{}",resp.block());
}
Copy the code
Download binary
- Download the pictures
@Test
public void testDownloadImage() throws IOException {
Mono<Resource> resp = WebClient.create().get()
.uri("http://www.toolip.gr/captcha?complexity=99&size=60&length=9")
.accept(MediaType.IMAGE_PNG)
.retrieve().bodyToMono(Resource.class);
Resource resource = resp.block();
BufferedImage bufferedImage = ImageIO.read(resource.getInputStream());
ImageIO.write(bufferedImage, "png", new File("captcha.png"));
}
Copy the code
- The download file
@Test
public void testDownloadFile() throws IOException {
Mono<ClientResponse> resp = WebClient.create().get()
.uri("http://localhost:8080/file/download")
.accept(MediaType.APPLICATION_OCTET_STREAM)
.exchange();
ClientResponse response = resp.block();
String disposition = response.headers().asHttpHeaders().getFirst(HttpHeaders.CONTENT_DISPOSITION);
String fileName = disposition.substring(disposition.indexOf("=") + 1); Resource resource = response.bodyToMono(Resource.class).block(); File out = new File(fileName); FileUtils.copyInputStreamToFile(resource.getInputStream(),out); LOGGER.info(out.getAbsolutePath()); }Copy the code
Error handling
@Test
public void testRetrieve4xx(){
WebClient webClient = WebClient.builder()
.baseUrl("https://api.github.com")
.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);
}
Copy the code
- You can use onStatus to perform an exception adaptation according to the Status code
- DoOnError exception adaptation can be used
- You can use onErrorReturn to return the default value
summary
Webclient is a new generation of Async REST templates, and its API is relatively simple and reactive, so it is worth using.
doc
- RestTemplate Example
- Decode ByteArray with spring 5 WebFlux framework