一区二区三区在线-一区二区三区亚洲视频-一区二区三区亚洲-一区二区三区午夜-一区二区三区四区在线视频-一区二区三区四区在线免费观看

服務器之家:專注于服務器技術及軟件下載分享
分類導航

PHP教程|ASP.NET教程|Java教程|ASP教程|編程技術|正則表達式|C/C++|IOS|C#|Swift|Android|VB|R語言|JavaScript|易語言|vb.net|

服務器之家 - 編程語言 - Java教程 - spring5 webclient使用指南詳解

spring5 webclient使用指南詳解

2021-03-25 10:42go4it Java教程

本篇文章主要介紹了spring 5 webclient使用指南詳解,小編覺得挺不錯的,現在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧

之前寫了一篇restTemplate使用實例,由于spring 5全面引入reactive,同時也有了restTemplate的reactive版webclient,本文就來對應展示下webclient的基本使用。

請求攜帶header

攜帶cookie

?
1
2
3
4
5
6
7
8
9
10
11
@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

?
1
2
3
4
5
6
7
8
9
10
11
12
@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

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
@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傳遞參數

?
1
2
3
4
5
6
7
8
9
10
11
@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傳遞參數

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
@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表單

?
1
2
3
4
5
6
7
8
9
10
11
12
@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

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
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

?
1
2
3
4
5
6
7
8
9
10
11
12
@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二進制--上傳文件

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
@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());
  }

下載二進制

下載圖片

?
1
2
3
4
5
6
7
8
9
10
11
@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"));
 
  }

下載文件

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
@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());
  }

錯誤處理

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
@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的,非常值得使用。

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。

原文鏈接:https://juejin.im/post/5a62f17cf265da3e51333205

延伸 · 閱讀

精彩推薦
主站蜘蛛池模板: japonensis日本护士 | 精品视频一区二区 | 国产高清路线一路线二2022 | freexxxxxhd张柏芝 | 亚洲精品无码不卡 | 97国产精品久久碰碰牛牛 | 亚洲香蕉视频 | 波多野结衣在线观看视频 | 粗了大了 整进去好爽视频 刺激一区仑乱 | 国产精品高清一区二区三区不卡 | 亚洲社区在线观看 | 波多野结衣在线中文 | 亚洲成人影院在线观看 | 波多野结衣在线看 | 人与动人物人a级特片 | 亚洲羞羞裸色私人影院 | 4虎影视国产在线观看精品 4s4s4s4s色大众影视 | 色网在线观看 | 女同性互吃奶乳免费视频 | 高h折磨调教古代 | 2020年精品国产午夜福利在线 | 99精品免费在线 | 日本亚洲娇小与黑人tube | 2022最新国产在线不卡a | 视频在线观看入口一二三2021 | 亚洲无线一二三四区 | 臀精插宫NP文| 国产日产欧产精品精品软件 | 91av俱乐部| 风间由美被义子中文字幕 | 99热这里只有精品国产在热久久 | 欧美一级裸片又黄又裸 | 国产良家| 精品国产免费第一区二区 | 日韩精品一区二区三区免费视频 | 无遮挡h肉动漫高清在线 | 精品国产成人a区在线观看 精品高潮呻吟99AV无码视频 | 国产成人综合亚洲一区 | 欧美亚洲另类综合 | 日本福利网 | 国内精品一区二区三区东京 |