热门标签 | HotTags
当前位置:  开发笔记 > 前端 > 正文

spring5webclient使用指南详解

之前写了一篇restTemplate使用实例,由于spring 5全面引入reactive,同时也有了restTemplate的reacti

之前写了一篇restTemplate使用实例,由于spring 5全面引入reactive,同时也有了restTemplate的reactive版webclient,本文就来对应展示下webclient的基本使用。

请求携带header

携带COOKIE

@Test
  public void testWithCOOKIE(){
    Mono 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 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 resp = webClient.get()
        .uri("https://baidu.com")
        .retrieve()
        .bodyToMono(String.class);
    LOGGER.info("result:{}",resp.block());
  }

get请求

使用placeholder传递参数

@Test
  public void testUrlPlaceholder(){
    Mono 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 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 formData = new LinkedMultiValueMap<>();
    formData.add("name1","value1");
    formData.add("name2","value2");
    Mono 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 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 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 entity = new HttpEntity<>(new ClassPathResource("parallel.png"), headers);
    MultiValueMap parts = new LinkedMultiValueMap<>();
    parts.add("file", entity);
    Mono 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 resp = WebClient.create().get()
        .uri("http://www.toolip.gr/captcha&#63;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 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&#63;sort={sortField}&direction={sortDirection}",
            "updated", "desc")
        .retrieve();
    Mono 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的,非常值得使用。

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


推荐阅读
  • 使用正则表达式爬取36Kr网站首页新闻的操作步骤和代码示例
    本文介绍了使用正则表达式来爬取36Kr网站首页所有新闻的操作步骤和代码示例。通过访问网站、查找关键词、编写代码等步骤,可以获取到网站首页的新闻数据。代码示例使用Python编写,并使用正则表达式来提取所需的数据。详细的操作步骤和代码示例可以参考本文内容。 ... [详细]
  • 本文由编程笔记#小编为大家整理,主要介绍了markdown[软件代理设置]相关的知识,希望对你有一定的参考价值。 ... [详细]
  • css元素可拖动,如何使用CSS禁止元素拖拽?
    一、用户行为三剑客以下3个CSS属性:user-select属性可以设置是否允许用户选择页面中的图文内容;user-modify属性可以设置是否允许输入 ... [详细]
  • Scrapy 爬取图片
    1.创建Scrapy项目scrapystartprojectCrawlMeiziTuscrapygenspiderMeiziTuSpiderhttps:movie.douban.c ... [详细]
  • 使用在线工具jsonschema2pojo根据json生成java对象
    本文介绍了使用在线工具jsonschema2pojo根据json生成java对象的方法。通过该工具,用户只需将json字符串复制到输入框中,即可自动将其转换成java对象。该工具还能解析列表式的json数据,并将嵌套在内层的对象也解析出来。本文以请求github的api为例,展示了使用该工具的步骤和效果。 ... [详细]
  • CSS|网格-行-结束属性原文:https://www.gee ... [详细]
  • 《Axure新技能:自适应手机屏幕大小》相信不少人都已经看过,并对设置方法已经很熟悉了,但该教程只能适应iphone6的屏幕尺寸的比例&# ... [详细]
  • 文章目录简介HTTP请求过程HTTP状态码含义HTTP头部信息Cookie状态管理HTTP请求方式简介HTTP协议(超文本传输协议)是用于从WWW服务 ... [详细]
  • 最近在学Python,看了不少资料、视频,对爬虫比较感兴趣,爬过了网页文字、图片、视频。文字就不说了直接从网页上去根据标签分离出来就好了。图片和视频则需要在获取到相应的链接之后取做下载。以下是图片和视 ... [详细]
  • 目录爬虫06scrapy框架1.scrapy概述安装2.基本使用3.全栈数据的爬取4.五大核心组件对象5.适当提升scrapy爬取数据的效率6.请求传参爬虫06scrapy框架1. ... [详细]
  • 篇首语:本文由编程笔记#小编为大家整理,主要介绍了正则表达式python相关的知识,希望对你有一定的参考价值。 ... [详细]
  • Material Design Lite ,简洁惊艳的前端工具箱。
    2019独角兽企业重金招聘Python工程师标准MaterialDesignLite简介本文主要介绍MaterialDesign设计语言的HTMLCSSJS部分实现。对应每一 ... [详细]
  • 微软头条实习生分享深度学习自学指南
    本文介绍了一位微软头条实习生自学深度学习的经验分享,包括学习资源推荐、重要基础知识的学习要点等。作者强调了学好Python和数学基础的重要性,并提供了一些建议。 ... [详细]
  • 目录实现效果:实现环境实现方法一:基本思路主要代码JavaScript代码总结方法二主要代码总结方法三基本思路主要代码JavaScriptHTML总结实 ... [详细]
  • pyecharts 介绍
    一、pyecharts介绍ECharts,一个使用JavaScript实现的开源可视化库,可以流畅的运行在PC和移动设备上,兼容当前绝大部 ... [详细]
author-avatar
-不寻常-
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有