spring boot使用WebClient调用HTTP服务代码示例
这篇文章主要介绍了springboot使用WebClient调用HTTP服务代码示例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
WebClient的请求模式属于异步非阻塞,能够以少量固定的线程处理高并发的HTTP请求
WebClient是SpringWebFlux模块提供的一个非阻塞的基于响应式编程的进行Http请求的客户端工具,从Spring5.0开始提供
在SpringBoot应用中
1.添加SpringWebFlux依赖
org.springframework.boot spring-boot-starter-webflux
2.使用
(1)Restful接口demoController.java
packagecom.example.demo.controller;
importcom.example.demo.domain.MyData;
importorg.springframework.http.HttpHeaders;
importorg.springframework.http.MediaType;
importorg.springframework.web.bind.annotation.*;
importjavax.servlet.http.Cookie;
importjavax.servlet.http.HttpServletRequest;
@RestController
@RequestMapping("/api")
publicclassdemoController{
@GetMapping(value="/getHeader",produces={MediaType.APPLICATION_JSON_UTF8_VALUE})
publicMyDatagetHeader(HttpServletRequestrequest){
intid=0;
if(request.getParameter("id")!=null){
id=Integer.valueOf(request.getParameter("id"));
}
Stringname=request.getParameter("name");
//header
StringuserAgent="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(Cookiecookie:cookies){
System.out.println(cookie.getName()+":"+cookie.getValue());
}
}
MyDatadata=newMyData();
data.setId(id);
data.setName(name);
data.setOther(userAgent);
returndata;
}
@PostMapping(value="/getPost",produces={MediaType.APPLICATION_JSON_UTF8_VALUE})
publicMyDatagetPost(HttpServletRequestrequest){
intid=0;
if(request.getParameter("id")!=null){
id=Integer.valueOf(request.getParameter("id"));
}
Stringname=request.getParameter("name");
System.out.println(name+","+id);
MyDatadata=newMyData();
data.setId(id);
data.setName(name);
returndata;
}
/**
*POST传JSON请求
*/
@PostMapping(value="/getPostJson",produces={MediaType.APPLICATION_JSON_UTF8_VALUE})
publicMyDatagetPostJson(@RequestBody(required=true)MyDatadata){
System.out.println(data.getId());
System.out.println(data.getName());
returndata;
}
}
MyData.java
packagecom.example.demo.domain;
publicclassMyData{
privateintid;
privateStringname;
privateStringother;
publicintgetId(){
returnid;
}
publicvoidsetId(intid){
this.id=id;
}
publicStringgetName(){
returnname;
}
publicvoidsetName(Stringname){
this.name=name;
}
publicStringgetOther(){
returnother;
}
publicvoidsetOther(Stringother){
this.other=other;
}
}
(2)WebClient使用
DemoApplicationTests.java
packagecom.example.demo;
importcom.example.demo.domain.MyData;
importorg.junit.Test;
importorg.springframework.http.HttpHeaders;
importorg.springframework.http.HttpMethod;
importorg.springframework.http.MediaType;
importorg.springframework.util.LinkedMultiValueMap;
importorg.springframework.util.MultiValueMap;
importorg.springframework.web.reactive.function.BodyInserters;
importorg.springframework.web.reactive.function.client.WebClient;
importreactor.core.publisher.Mono;
importjava.time.Duration;
importjava.time.temporal.ChronoUnit;
publicclassDemoApplicationTests{
privateWebClientwebClient=WebClient.builder()
.baseUrl("http://127.0.0.1:8080")
.defaultHeader(HttpHeaders.USER_AGENT,"Mozilla/5.0(WindowsNT10.0;WOW64)AppleWebKit/537.36(KHTML,likeGecko)")
.defaultCookie("ACCESS_TOKEN","test_token").build();
@Test
publicvoidWebGetDemo(){
try{
Monoresp=webClient.method(HttpMethod.GET).uri("api/getHeader?id={id}&name={name}",123,"abc")
.retrieve()
.bodyToMono(MyData.class);
MyDatadata=resp.block();
System.out.println("WebGetDemoresult-----"+data.getString());
}catch(Exceptione){
e.printStackTrace();
}
}
@Test
publicvoidWebPostDemo(){
MultiValueMapformData=newLinkedMultiValueMap<>(2);
formData.add("id","456");
formData.add("name","xyz");
Monoresponse=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);
MyDatadata=response.block();
System.out.println("WebPostDemoresult-----"+data.getString());
}
@Test
publicvoidWebPostJson(){
MyDatarequestData=newMyData();
requestData.setId(789);
requestData.setName("lmn");
Monoresponse=webClient.post().uri("/api/getPostJson")
.contentType(MediaType.APPLICATION_JSON_UTF8)
.syncBody(requestData)
.retrieve()
.bodyToMono(MyData.class).timeout(Duration.of(10,ChronoUnit.SECONDS));
MyDatadata=response.block();
System.out.println("WebPostJsonresult-----"+data.getString());
}
}
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。