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)文章
SpringBoot在自定義類中調(diào)用service層等Spring其他層操作
這篇文章主要介紹了SpringBoot在自定義類中調(diào)用service層等Spring其他層操作,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-06-06
springboot運(yùn)行時(shí)新增/更新外部接口的實(shí)現(xiàn)方法
這篇文章主要介紹了springboot運(yùn)行時(shí)新增/更新外部接口的實(shí)現(xiàn)方法,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2021-03-03
springboot獲取properties屬性值的多種方式總結(jié)
這篇文章主要介紹了springboot獲取properties屬性值的多種方式總結(jié),具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-03-03
Spring Boot集成Swagger接口分類與各元素排序問題
這篇文章主要介紹了Spring Boot集成Swagger接口分類與各元素排序問題,首先我們需要對(duì)Swagger中的接口也就是以Controller 層作為第一級(jí)梯度進(jìn)行組織的,Controller在我們實(shí)際開發(fā)中,與其他具體接口之間是存在一對(duì)多的關(guān)系,本文給大家介紹的非常詳細(xì),需要的朋友參考下吧2023-10-10
詳解Java編程中final,finalize,finally的區(qū)別
這篇文章主要介紹了詳解Java編程中final,finalize,finally的區(qū)別,這個(gè)在Java面試題中簡(jiǎn)直是太常見了...需要的朋友可以參考下2015-11-11

