欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

spring5 webclient使用指南詳解

 更新時間:2018年01月22日 10:43:12   作者:go4it  
本篇文章主要介紹了spring 5 webclient使用指南詳解,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧

之前寫了一篇restTemplate使用實例,由于spring 5全面引入reactive,同時也有了restTemplate的reactive版webclient,本文就來對應(yīng)展示下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());
  }

設(shè)置全局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傳遞參數(shù)

@Test
  public void testUrlPlaceholder(){
    Mono<String> resp = WebClient.create()
        .get()
        //多個參數(shù)也可以直接放到map中,參數(shù)名與placeholder對應(yīng)上即可
        .uri("http://www.baidu.com/s?wd={key}&other={another}","北京天氣","test") //使用占位符
        .retrieve()
        .bodyToMono(String.class);
    LOGGER.info("result:{}",resp.block());

  }

使用uriBuilder傳遞參數(shù)

@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二進(jìn)制--上傳文件

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

下載二進(jìn)制

下載圖片

@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根據(jù)status code進(jìn)行異常適配
  2. 可以使用doOnError異常適配
  3. 可以使用onErrorReturn返回默認(rèn)值

小結(jié)

webclient是新一代的async rest template,api也相對簡潔,而且是reactive的,非常值得使用。

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

  • Java排序算法之選擇排序

    Java排序算法之選擇排序

    這篇文章主要介紹了Java排序算法之選擇排序,文中有非常詳細(xì)的代碼示例,對正在學(xué)習(xí)java的小伙伴們有非常好的幫助,需要的朋友可以參考下
    2021-05-05
  • Spring Cloud Hystrix 服務(wù)容錯保護(hù)的原理實現(xiàn)

    Spring Cloud Hystrix 服務(wù)容錯保護(hù)的原理實現(xiàn)

    這篇文章主要介紹了Spring Cloud Hystrix 服務(wù)容錯保護(hù)的原理實現(xiàn),小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2019-05-05
  • 一文詳解Java方法重載與遞歸應(yīng)用

    一文詳解Java方法重載與遞歸應(yīng)用

    方法重載 允許在同一個類中定義多個具有相同名稱的方法,但 參數(shù)列表 必須不同,遞歸 是一種讓函數(shù)調(diào)用自身的技術(shù),它提供了一種將復(fù)雜問題分解為簡單問題的方法,這樣更容易解決,本文詳細(xì)介紹了Java方法重載與遞歸應(yīng)用,需要的朋友可以參考下
    2024-02-02
  • Java防止頻繁請求、重復(fù)提交的操作代碼(后端防抖操作)

    Java防止頻繁請求、重復(fù)提交的操作代碼(后端防抖操作)

    在客戶端網(wǎng)絡(luò)慢或者服務(wù)器響應(yīng)慢時,用戶有時是會頻繁刷新頁面或重復(fù)提交表單的,這樣是會給服務(wù)器造成不小的負(fù)擔(dān)的,同時在添加數(shù)據(jù)時有可能造成不必要的麻煩,今天通過本文給大家介紹下Java防止頻繁請求、重復(fù)提交的操作代碼,一起看看吧
    2022-04-04
  • SpringBoot在線代碼修改器的問題及解決方法

    SpringBoot在線代碼修改器的問題及解決方法

    這篇文章主要介紹了SpringBoot在線代碼修改器的問題及解決方法,本文通過實例代碼給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2020-06-06
  • java生成csv文件亂碼的解決方法示例 java導(dǎo)出csv亂碼

    java生成csv文件亂碼的解決方法示例 java導(dǎo)出csv亂碼

    這篇文章主要介紹了java生成csv文件亂碼的解決方法,大家可以直接看下面的示例
    2014-01-01
  • MybatisPlus 自動填充的實現(xiàn)

    MybatisPlus 自動填充的實現(xiàn)

    這篇文章主要介紹了MybatisPlus 自動填充的實現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2020-09-09
  • Java并發(fā)編程之線程創(chuàng)建介紹

    Java并發(fā)編程之線程創(chuàng)建介紹

    這篇文章主要介紹了Java并發(fā)編程之線程創(chuàng)建,進(jìn)程是代碼在數(shù)據(jù)集合上的一次運行活動,是系統(tǒng)進(jìn)行資源分配和調(diào)度的基本單位,線程則是一個實體,一個進(jìn)程中至少有一個線程,下文更多相關(guān)內(nèi)容需要的小伙伴可以參考一下
    2022-04-04
  • Java生成隨機(jī)姓名、性別和年齡的實現(xiàn)示例

    Java生成隨機(jī)姓名、性別和年齡的實現(xiàn)示例

    這篇文章主要介紹了Java生成隨機(jī)姓名、性別和年齡的實現(xiàn)示例,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2020-09-09
  • 談?wù)勀憧赡懿⒉涣私獾膉ava枚舉

    談?wù)勀憧赡懿⒉涣私獾膉ava枚舉

    這篇文章主要給大家介紹了一些關(guān)于你可能并不了解的java枚舉的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2020-09-09

最新評論