spring5 webclient使用指南详解

 更新时间:2018年01月22日 10:43:12   作者:go4it  
本篇文章主要介绍了spring 5 webclient使用指南详解,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧

之前写了一篇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://www.baidu.com/s?wd={key}&other={another}","北京天气","test") //使用占位符
        .retrieve()
        .bodyToMono(String.class);
    LOGGER.info("result:{}",resp.block());

  }

使用uriBuilder传递参数

@Test
  public void testUrlBiulder(){
    Mono<String> resp = WebClient.create()
        .get()
        .uri(uriBuilder -> uriBuilder
            .scheme("http")
            .host("www.baidu.com")
            .path("/s")
            .queryParam("wd", "北京天气")
            .queryParam("other", "test")
            .build())
        .retrieve()
        .bodyToMono(String.class);
    LOGGER.info("result:{}",resp.block());
  }

post表单

@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());
  }

post json

使用bean来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());
  }

直接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());
  }

post二进制--上传文件

@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());
  }

下载二进制

下载图片

@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"));

  }

下载文件

@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());
  }

错误处理

@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);
  }
  1. 可以使用onStatus根据status code进行异常适配
  2. 可以使用doOnError异常适配
  3. 可以使用onErrorReturn返回默认值

小结

webclient是新一代的async rest template,api也相对简洁,而且是reactive的,非常值得使用。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

相关文章

  • Java文件基本操作总结

    Java文件基本操作总结

    今天给大家带来的是关于Java基础的相关知识,文章围绕着Java文件操作展开,文中有非常详细的介绍及代码示例,需要的朋友可以参考下
    2021-06-06
  • 浅谈java安全编码指南之堆污染

    浅谈java安全编码指南之堆污染

    什么是堆污染呢?是指当参数化类型变量引用的对象不是该参数化类型的对象时而发生的。我们知道在JDK5中,引入了泛型的概念,在创建集合类的时候,指定该集合类中应该存储的对象类型。如果在指定类型的集合中,引用了不同的类型,那么这种情况就叫做堆污染。
    2021-06-06
  • java性能优化之编译器版本与平台对应关系

    java性能优化之编译器版本与平台对应关系

    这篇文章主要介绍了java性能优化--编译器版本与平台对应关系,本章节更加具体化的学习编译器还有哪些可以优化的方便,让你的应用展现出更好的性能,需要的朋友可以参考下
    2022-06-06
  • SpringCloud服务网关Gateway的使用教程详解

    SpringCloud服务网关Gateway的使用教程详解

    SpringCloud Gateway是Spring体系内的一个全新项目,它旨在为微服务架构提供一种简单有效的统一的API路由管理方式。本文就来为大家详细讲讲Gateway的使用教程,需要的可以参考一下
    2022-09-09
  • 深入理解JAVA 备忘录模式

    深入理解JAVA 备忘录模式

    这篇文章主要介绍了JAVA 备忘录模式的的相关资料,文中示例代码非常细致,供大家参考和学习,感兴趣的朋友可以了解下
    2020-06-06
  • RestTemplate get请求携带headers自动拼接参数方式

    RestTemplate get请求携带headers自动拼接参数方式

    这篇文章主要介绍了RestTemplate get请求携带headers自动拼接参数方式,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2023-07-07
  • Java Spring MVC 上传下载文件配置及controller方法详解

    Java Spring MVC 上传下载文件配置及controller方法详解

    这篇文章主要介绍了Java Spring MVC 上传下载文件配置及controller方法详解,本文介绍的非常详细,具有参考借鉴价值,需要的朋友可以参考下
    2016-09-09
  • SpringBoot 钩子接口的实现代码

    SpringBoot 钩子接口的实现代码

    本文主要介绍了SpringBoot 钩子接口,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2021-08-08
  • Spring @Cacheable指定失效时间实例

    Spring @Cacheable指定失效时间实例

    这篇文章主要介绍了Spring @Cacheable指定失效时间实例,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2021-12-12
  • Spring Data JPA框架的核心概念与Repository接口详解

    Spring Data JPA框架的核心概念与Repository接口详解

    Spring Data JPA是Spring基于JPA规范的基础上封装的⼀套 JPA 应⽤框架,可使开发者⽤极简的代码即可实现对数据库的访问和操作,本篇我们来了解Spring Data JPA框架的核心概念与Repository接口
    2022-04-04

最新评论