java webclient使用_spring5 webclient使用指南详解
之前写了一篇resttemplate使用实例,由于spring 5全面引入reactive,同时也有了resttemplate的reactive版webclient,本文就来对应展示下webclient的基本使用。
请求携带header
携带cookie
@test
public void testwithcookie(){
mono 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 resp = webclient.create()
.get()
.uri("http://baidu.com")
.header(httpheaders.authorization,basicauth)
.retrieve()
.bodytomono(string.class);
logger.info("result:{}",resp.block());
}
设置全局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 resp = webclient.get()
.uri("https://baidu.com")
.retrieve()
.bodytomono(string.class);
logger.info("result:{}",resp.block());
}
get请求
使用placeholder传递参数
@test
public void testurlplaceholder(){
mono resp = webclient.create()
.get()
//多个参数也可以直接放到map中,参数名与placeholder对应上即可
.uri("http://www.baidu.com/s?wd={key}&other={another}","北京天气","test") //使用占位符
.retrieve()
.bodytomono(string.class);
logger.info("result:{}",resp.block());
}
使用uribuilder传递参数
@test
public void testurlbiulder(){
mono 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 formdata = new linkedmultivaluemap<>();
formdata.add("name1","value1");
formdata.add("name2","value2");
mono 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 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 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二进制--上传文件
@test
public void testuploadfile(){
httpheaders headers = new httpheaders();
headers.setcontenttype(mediatype.image_png);
httpentity entity = new httpentity<>(new classpathresource("parallel.png"), headers);
multivaluemap parts = new linkedmultivaluemap<>();
parts.add("file", entity);
mono 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());
}
下载二进制
下载图片
@test
public void testdownloadimage() throws ioexception {
mono 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 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 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);
}
可以使用onstatus根据status code进行异常适配
可以使用doonerror异常适配
可以使用onerrorreturn返回默认值
小结
webclient是新一代的async rest template,api也相对简洁,而且是reactive的,非常值得使用。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持萬仟网。
希望与广大网友互动??
点此进行留言吧!
java webclient使用_spring5 webclient使用指南详解相关推荐
- easyExcel 使用指南详解
来源:easyExcel 使用指南详解 - 知乎 easyExcel简介 Java领域解析.生成Excel比较有名的框架有Apache poi.jxl等.但他们都存在一个严重的问题就是非常的耗内存.如 ...
- java写exe程序实例,java实现可安装的exe程序实例详解
java实现可安装的exe程序实例详解 通过编写java代码,实现可安装的exe文件的一般思路: 1.在eclipse中创建java项目,然后编写java代码,将编写好的java项目导出一个.jar格 ...
- 把java文件打包成.jar (jar命令详解)
把java文件打包成.jar (jar命令详解) 先打开命令提示符(win2000或在运行框里执行cmd命令,win98为DOS提示符),输入jar Chelp,然后回车(如果你盘上已经有了jdk1. ...
- 2020年 第11届 蓝桥杯 Java B组 省赛真题详解及小结【第1场省赛 2020.7.5】
蓝桥杯 Java B组 省赛决赛 真题详解及小结汇总[2013年(第4届)~2021年(第12届)] 第11届 蓝桥杯-第1.2次模拟(软件类)真题-(2020年3月.4月)-官方讲解视频 说明:部分 ...
- 2020年 第11届 蓝桥杯 Java C组 省赛真题详解及小结【第1场省赛 2020.7.5】
蓝桥杯 Java B组 省赛真题详解及小结汇总[2013年(第4届)~2020年(第11届)] 注意:部分代码及程序 源自 蓝桥杯 官网视频(历年真题解析) 郑未老师. 2013年 第04届 蓝桥杯 ...
- 2019年 第10届 蓝桥杯 Java B组 省赛真题详解及总结
蓝桥杯 Java B组 省赛真题详解及小结汇总[2013年(第4届)~2020年(第11届)] 注意:部分代码及程序 源自 蓝桥杯 官网视频(历年真题解析) 郑未老师. 2013年 第04届 蓝桥杯 ...
- 2018年 第9届 蓝桥杯 Java B组 省赛真题详解及总结
蓝桥杯 Java B组 省赛决赛 真题详解及小结汇总[2013年(第4届)~2021年(第12届)] 第11届 蓝桥杯-第1.2次模拟(软件类)真题-(2020年3月.4月)-官方讲解视频 说明:部分 ...
- Java垃圾回收(GC)机制详解
Java垃圾回收(GC)机制详解 转自:https://www.cnblogs.com/xiaoxi/p/6486852.html 一.为什么需要垃圾回收 如果不进行垃圾回收,内存迟早都会被消耗空,因 ...
- Java经典面试题整理及答案详解(八)
简介: Java经典面试题第八节来啦!本节面试题包含了进程.线程.Object类.虚拟内存等相关内容,希望大家多多练习,早日拿下心仪offer- 了解更多: Java经典面试题整理及答案详解(一) J ...
- Java经典面试题整理及答案详解(三)
简介: 以下是某同学面试时,面试官问到的问题,关于面试题答案可以参考以下内容- 上一篇:Java经典面试题整理及答案详解(二) Java面试真题第三弹接住!相信通过前两节的学习,大家对于Java多少有 ...
最新文章
- 将二进制流转换为图片
- 当我们在谈深度学习时,到底在谈论什么(三)--转
- 数据中心空调系统中的冷却塔应用手册
- 史上最全JS表单验证封装类
- postgresql操作
- 【Boost】boost库中thread多线程详解12——线程的分离与非分离
- mvc 之 配置EF+oralce
- Net中的AOP系列之《将AOP作为架构工具》
- “21天好习惯“第一期-5
- vmware workstation 12安装ubuntu kylin 16.04虚拟机
- 自己制作的4X4光立方焊接时候出现的问题
- javascript实现简单的新消息语音提醒功能
- Android 8.0中各种通知写法汇总
- TAM: Temporal Adaptive Module for Video Recognition论文学习
- select 检索数据
- ukf源程序 matlab,《卡尔曼滤波原理及应用-MATLAB仿真》程序-5.1UKF
- springboot水产品销售系统的设计与实现毕业设计源码041700
- 关注物联网、关注NB-IoT
- 用matlab画一些骚东西,求助matlab大神,学校的课程安排太骚了,我们压根就不用学matlab...
- 《架构即未来》-技术与商业须融汇贯通!前eBay CTO的实战真经
热门文章
- 多网融合消防无线应急通信系统
- drupal上安装chatroom
- 水果店水果打理方法有哪些
- python判断字符串包含中文_高手接招! 小应用 用python3判断一个字符串是不是中文组成的...
- Probabilistic and Geometric Depth: Detecting Objects in Perspective 论文学习
- 榆林市科技馆项目的变电所运维
- centos-安装并使用五笔输入法-极点五笔输入法
- 软件测试-3-随机测试
- 结合论文理解gps与imu融合定位代码的细节
- Py3+Django 获取Foursquare的Check-in History