spring boot使用WebClient調(diào)用HTTP服務(wù)代碼示例
這篇文章主要介紹了spring boot使用WebClient調(diào)用HTTP服務(wù)代碼示例,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
WebClient的請(qǐng)求模式屬于異步非阻塞,能夠以少量固定的線程處理高并發(fā)的HTTP請(qǐng)求
WebClient是Spring WebFlux模塊提供的一個(gè)非阻塞的基于響應(yīng)式編程的進(jìn)行Http請(qǐng)求的客戶端工具,從Spring5.0開始提供
在Spring Boot應(yīng)用中
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請(qǐng)求
*/
@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());
}
}
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
java如何更改數(shù)據(jù)庫(kù)中的數(shù)據(jù)
這篇文章主要介紹了java如何更改數(shù)據(jù)庫(kù)中的數(shù)據(jù),修改數(shù)據(jù)庫(kù)是數(shù)據(jù)庫(kù)操作必不可少的一部分,使用Statement接口中的excuteUpdate()方法可以修改數(shù)據(jù)表中的數(shù)據(jù),感興趣的朋友跟隨小編一起看看吧2021-11-11
maven父子工程多模塊統(tǒng)一管理版本號(hào)的解決方法
maven父子工程多模塊,每個(gè)模塊還都可以獨(dú)立存在,子模塊往往通常希望和父工程保持一樣的版本,如果每個(gè)工程單獨(dú)定義版本號(hào),后期變更打包也非常麻煩,,所以本文給大家介紹了maven父子工程多模塊如何管理統(tǒng)一的版本號(hào),需要的朋友可以參考下2024-09-09
Mybatis插件+注解實(shí)現(xiàn)數(shù)據(jù)脫敏方式
這篇文章主要介紹了Mybatis插件+注解實(shí)現(xiàn)數(shù)據(jù)脫敏方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-09-09
java中對(duì)象和JSON格式的轉(zhuǎn)換方法代碼
JSON格式可以輕松地以面向?qū)ο蟮姆绞睫D(zhuǎn)換為Java對(duì)象,下面這篇文章主要給大家介紹了關(guān)于java中對(duì)象和JSON格式的轉(zhuǎn)換方法,文中通過代碼介紹的非常詳細(xì),需要的朋友可以參考下2023-12-12
Intellij IDEA解析jacoco結(jié)果文件的方法
這篇文章主要介紹了Intellij IDEA解析jacoco結(jié)果文件的方法,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-09-09
Mybatis動(dòng)態(tài)Sql標(biāo)簽使用小結(jié)
本文主要介紹了Mybatis動(dòng)態(tài)Sql標(biāo)簽使用,常用的動(dòng)態(tài)sql標(biāo)簽包括?if、choose(when、otherwise)、trim(where、set)、foreach,下面就來介紹一下2024-04-04

