您好,登錄后才能下訂單哦!
怎么在spring boot中利用WebClient對HTTP服務進行調用?很多新手對此不是很清楚,為了幫助大家解決這個難題,下面小編將為大家詳細講解,有這方面需求的人可以來學習下,希望你能有所收獲。
WebClient的請求模式屬于異步非阻塞,能夠以少量固定的線程處理高并發的HTTP請求
WebClient是Spring WebFlux模塊提供的一個非阻塞的基于響應式編程的進行Http請求的客戶端工具,從Spring5.0開始提供
在Spring Boot應用中
1.添加Spring WebFlux依賴
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-webflux</artifactId> </dependency>
2.使用
(1)Restful接口demoController.java
package com.example.demo.controller; import com.example.demo.domain.MyData; import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.*; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; @RestController @RequestMapping("/api") public class demoController { @GetMapping(value = "/getHeader", produces = {MediaType.APPLICATION_JSON_UTF8_VALUE}) public MyData getHeader(HttpServletRequest request) { int id = 0; if (request.getParameter("id") != null) { id = Integer.valueOf(request.getParameter("id")); } String name = request.getParameter("name"); //header String userAgent = "USER_AGENT——" + request.getHeader(HttpHeaders.USER_AGENT); userAgent += " | ACCEPT_CHARSET——" + request.getHeader(HttpHeaders.ACCEPT_CHARSET); userAgent += " | ACCEPT_ENCODING——" + request.getHeader(HttpHeaders.ACCEPT_ENCODING); userAgent += " | ContextPath——" + request.getContextPath(); userAgent += " | AuthType——" + request.getAuthType(); userAgent += " | PathInfo——" + request.getPathInfo(); userAgent += " | Method——" + request.getMethod(); userAgent += " | QueryString——" + request.getQueryString(); Cookie[] cookies = request.getCookies(); if (cookies != null) { for (Cookie cookie : cookies) { System.out.println(cookie.getName() + ":" + cookie.getValue()); } } MyData data = new MyData(); data.setId(id); data.setName(name); data.setOther(userAgent); return data; } @PostMapping(value = "/getPost", produces = {MediaType.APPLICATION_JSON_UTF8_VALUE}) public MyData getPost(HttpServletRequest request) { int id = 0; if (request.getParameter("id") != null) { id = Integer.valueOf(request.getParameter("id")); } String name = request.getParameter("name"); System.out.println(name + "," + id); MyData data = new MyData(); data.setId(id); data.setName(name); return data; } /** * POST傳JSON請求 */ @PostMapping(value = "/getPostJson", produces = {MediaType.APPLICATION_JSON_UTF8_VALUE}) public MyData getPostJson(@RequestBody(required = true) MyData data) { System.out.println(data.getId()); System.out.println(data.getName()); return data; } }
MyData.java
package com.example.demo.domain; public class MyData { private int id; private String name; private String other; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getOther() { return other; } public void setOther(String other) { this.other = other; } }
(2)WebClient使用
DemoApplicationTests.java
package com.example.demo; import com.example.demo.domain.MyData; import org.junit.Test; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.http.MediaType; import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; import org.springframework.web.reactive.function.BodyInserters; import org.springframework.web.reactive.function.client.WebClient; import reactor.core.publisher.Mono; import java.time.Duration; import java.time.temporal.ChronoUnit; public class DemoApplicationTests { private WebClient webClient = WebClient.builder() .baseUrl("http://127.0.0.1:8080") .defaultHeader(HttpHeaders.USER_AGENT, "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko)") .defaultCookie("ACCESS_TOKEN", "test_token").build(); @Test public void WebGetDemo() { try { Mono<MyData> resp = webClient.method(HttpMethod.GET).uri("api/getHeader?id={id}&name={name}", 123, "abc") .retrieve() .bodyToMono(MyData.class); MyData data = resp.block(); System.out.println("WebGetDemo result----- " + data.getString()); } catch (Exception e) { e.printStackTrace(); } } @Test public void WebPostDemo() { MultiValueMap<String, String> formData = new LinkedMultiValueMap<>(2); formData.add("id", "456"); formData.add("name", "xyz"); Mono<MyData> response = webClient.method(HttpMethod.POST).uri("/api/getPost") .contentType(MediaType.APPLICATION_FORM_URLENCODED) .body(BodyInserters.fromFormData(formData)) .retrieve() .bodyToMono(MyData.class).timeout(Duration.of(10, ChronoUnit.SECONDS)); System.out.println(response); MyData data = response.block(); System.out.println("WebPostDemo result----- " + data.getString()); } @Test public void WebPostJson() { MyData requestData = new MyData(); requestData.setId(789); requestData.setName("lmn"); Mono<MyData> response = webClient.post().uri("/api/getPostJson") .contentType(MediaType.APPLICATION_JSON_UTF8) .syncBody(requestData) .retrieve() .bodyToMono(MyData.class).timeout(Duration.of(10, ChronoUnit.SECONDS)); MyData data = response.block(); System.out.println("WebPostJson result----- " + data.getString()); } }
看完上述內容是否對您有幫助呢?如果還想對相關知識有進一步的了解或閱讀更多相關文章,請關注億速云行業資訊頻道,感謝您對億速云的支持。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。