Vert.x WebClient WebClientOptions

本文参考自Vert.x Web Client官方文档。套用官网的话来说,

Vert.x Web Client是一个异步的HTTP和HTTP/2网络客户端。

相对来说,这是一个比较小的框架,而且功能也很直接,做一个方便好用的HTTP客户端。它具有以下功能:

Json body 编码 / 解码
request 参数
统一的错误处理
表单提交
需要注意,它和Vertx核心包中的HttpClient有很多联系。它继承了HttpClient,提供了更多功能。

引用类库
要使用这个类库很简单。如果使用Maven,添加下面的依赖。

<dependency>
<groupId>io.vertx</groupId>
<artifactId>vertx-web-client</artifactId>
<version>3.4.2</version>
</dependency>
 
如果使用Gradle,添加下面的依赖。

dependencies {
compile ‘io.vertx:vertx-web-client:3.4.2‘
}
 
创建客户端
创建客户端稍微有点不一样。

WebClient client = WebClient.create(vertx);
 
如果要添加配置参数,可以这样做。

WebClientOptions options = new WebClientOptions()
.setUserAgent("My-App/1.2.3");
options.setKeepAlive(false);
WebClient client = WebClient.create(vertx, options);
 
如果已经有了HttpClient,可以重用它。

WebClient client = WebClient.wrap(httpClient); 
发起请求
无请求体的请求
这是最简单的情况,一般的GET、HEAD等请求都输这种方式。

webClient.get("www.baidu.com", "/")
.send(ar -> {
if (ar.succeeded()) {
HttpResponse<Buffer> response = ar.result();
System.out.println(response.body());
} else {
System.out.println(ar.cause());
}
});
 
如果要携带查询参数,可以采用流式API。

client
.get(8080, "myserver.mycompany.com", "/some-uri")
.addQueryParam("param", "param_value")
.send(ar -> {});
 
也可以直接在URL中设置查询参数。

HttpRequest<Buffer> request = client.get(8080, "myserver.mycompany.com", "/some-uri");

// 添加参数1
request.addQueryParam("param1", "param1_value");

// 用URL覆盖参数
request.uri("/some-uri?param1=param1_value&param2=param2_value");
 
添加请求体
假如使用POST方式传递参数,或者上传图片等,就需要带有请求体的请求了。这种情况下,只需要额外使用sendXXX等方法添加要传递的请求体即可。

webClient.post("httpbin.org", "/post")
.sendBuffer(Buffer.buffer("name=yitian&age=25"), ar -> {
if (ar.succeeded()) {
HttpResponse<Buffer> response = ar.result();
System.out.println(response.body());
}
});
 
如果要发送的信息比较大,可以使用sendStream方法,使用流来传输数据。

client
.post(8080, "myserver.mycompany.com", "/some-uri")
.sendStream(stream, resp -> {});
 
Json请求体
有时候可能需要发送Json数据,这时候可以使用sendJsonObject方法。

client
.post(8080, "myserver.mycompany.com", "/some-uri")
.sendJsonObject(new JsonObject()
.put("firstName", "Dale")
.put("lastName", "Cooper"), ar -> {
if (ar.succeeded()) {
// Ok
}
});
 
发送表单
发送表单使用sendForm方法。

MultiMap multiMap = MultiMap.caseInsensitiveMultiMap();
multiMap.add("name", "yitian");
multiMap.add("age", "25");
webClient.post("httpbin.org", "/post")
.sendForm(multiMap, ar -> {
if (ar.succeeded()) {
HttpResponse<Buffer> response = ar.result();
System.out.println(response.body());
}
});
 
默认表单使用application/x-www-form-urlencoded类型的Content Type发送,也可以修改成multipart/form-data类型。

client
.post(8080, "myserver.mycompany.com", "/some-uri")
.putHeader("content-type", "multipart/form-data")
.sendForm(form, ar -> {
if (ar.succeeded()) {
// Ok
}
});
 
目前上传文件还不支持,将会在以后的版本中支持上传文件。

修改请求头
可以添加和修改要发送的请求头。

HttpRequest<Buffer> request = client.get(8080, "myserver.mycompany.com", "/some-uri");
MultiMap headers = request.headers();
headers.set("content-type", "application/json");
headers.set("other-header", "foo");
 
也可以调用putHeader方法直接添加请求头。

HttpRequest<Buffer> request = client.get(8080, "myserver.mycompany.com", "/some-uri");
request.putHeader("content-type", "application/json");
request.putHeader("other-header", "foo");
 
重用请求
如果需要对同一个地址发起多次请求,我们可以设置一次请求,然后重复使用它。

HttpRequest<Buffer> get = client.get(8080, "myserver.mycompany.com", "/some-uri");
get.send(ar -> {
if (ar.succeeded()) {
// Ok
}
});

// 重复使用
get.send(ar -> {
if (ar.succeeded()) {
// Ok
}
});
  
超时
发起请求的时候可以设置超时值,单位是毫秒。

client
.get(8080, "myserver.mycompany.com", "/some-uri")
.timeout(5000)
.send(ar -> {
if (ar.succeeded()) {
// Ok
} else {
// Might be a timeout when cause is java.util.concurrent.TimeoutException
}
});
 
处理请求
处理请求也是异步的。这里的ar类型实际是AsyncResult的类型,代表异步结果。如果结果成功了,调用result()方法返回HttpResponse<Buffer>类型对象,这就是我们发起请求的结果,调用statusCode()、body()等方法就可以查看相应结果了。

webClient.get("www.baidu.com", "/")
.send(ar -> {
if (ar.succeeded()) {
HttpResponse<Buffer> response = ar.result();
System.out.println(response.body());
} else {
System.out.println(ar.cause());
}
});
 
解码响应
前面的响应是以Buffer形式返回的。如果我们确定响应是普通字符串、Json对象、可以和Json映射的POJO类以及WriteStream,我们还可以解码响应。例如下面就将响应体解码为了JsonObject对象。

webClient.post("httpbin.org", "/post")
.as(BodyCodec.jsonObject())
.sendBuffer(Buffer.buffer("name=yitian&age=25"), ar -> {
if (ar.succeeded()) {
HttpResponse<JsonObject> response = ar.result();
System.out.println(response.body());
}
});
 
BodyCodec类还有另外几个方法,可以将响应体解码为不同类型。假如响应体比较大,可以直接将响应体转换为输出流,以后慢慢读取。

client
.get(8080, "myserver.mycompany.com", "/some-uri")
.as(BodyCodec.pipe(writeStream))
.send(ar -> {
if (ar.succeeded()) {

HttpResponse<Void> response = ar.result();

System.out.println("Received response with status code" + response.statusCode());
} else {
System.out.println("Something went wrong " + ar.cause().getMessage());
}
});
 
如果确定不需要响应体,可以直接用none()方法扔掉响应体。

client
.get(8080, "myserver.mycompany.com", "/some-uri")
.as(BodyCodec.none())
.send(ar -> {
if (ar.succeeded()) {

HttpResponse<Void> response = ar.result();

System.out.println("Received response with status code" + response.statusCode());
} else {
System.out.println("Something went wrong " + ar.cause().getMessage());
}
});
 
当然,如果响应体还是解码为Buffer,我们仍然可以调用bodyAsXXX方法来解码响应体。这种方法仅适用于Buffer响应体。

client
.get(8080, "myserver.mycompany.com", "/some-uri")
.send(ar -> {
if (ar.succeeded()) {

HttpResponse<Buffer> response = ar.result();

// Decode the body as a json object
JsonObject body = response.bodyAsJsonObject();

System.out.println("Received response with status code" + response.statusCode() + " with body " + body);
} else {
System.out.println("Something went wrong " + ar.cause().getMessage());
}
});
 
使用HTTPS
前面使用的都是普通的HTTP,如果要使用HTTPS连接也很容易,将端口号指定为443即可。

client
.get(443, "myserver.mycompany.com", "/some-uri")
.ssl(true)
.send(ar -> {
if (ar.succeeded()) {
// Obtain response
HttpResponse<Buffer> response = ar.result();

System.out.println("Received response with status code" + response.statusCode());
} else {
System.out.println("Something went wrong " + ar.cause().getMessage());
}
}); 
或者使用绝对路径标志的URI也可以。

client
.getAbs("https://myserver.mycompany.com:4043/some-uri")
.send(ar -> {
if (ar.succeeded()) {
// Obtain response
HttpResponse<Buffer> response = ar.result();

System.out.println("Received response with status code" + response.statusCode());
} else {
System.out.println("Something went wrong " + ar.cause().getMessage());
}
});

原文地址:https://www.cnblogs.com/endv/p/12601902.html

时间: 2024-08-08 14:07:47

Vert.x WebClient WebClientOptions的相关文章

Vert.x学习之 Web Client

Vert.x Web Client 原文档 组件源码 组件示例 中英对照表 Pump:泵(平滑流式数据读入内存的机制,防止一次性将大量数据读入内存导致内存溢出) Response Codec:响应编解码器(编码及解码工具) Body Codec:响应体编解码器 组件介绍 Vert.x Web Client(Web客户端)是一个异步的 HTTP 和 HTTP/2 客户端. Web Client使得发送 HTTP 请求以及从 Web 服务器接收 HTTP 响应变得更加便捷,同时提供了额外的高级功能,

C#利用WebClient 两种方式下载文件

WebClient client = new WebClient(); 第一种 string URLAddress = @"http://files.cnblogs.com/x4646/tree.zip"; string [email protected]"C:\"; client.DownloadFile(URLAddress, receivePath + System.IO.Path.GetFileName(URLAddress)); 就OK了. 第二种 Str

wp8通过WebClient从服务器下载文件

通过WebClient从Web服务器下载文件,并保存到wp8手机应用程序的独立存储. 我们可以通过利用webClient_DownloadStringCompleted来获得下载完成所需要的时间,用Stopwatch得到下载的总时间. 通常我们都将上传.下载作为异步事件来处理,以便不阻止主线程. String url = "http://172.18.144.248:8080/upload/" + filename; WebClient client = new WebClient()

winform下通过webclient使用非流方式上传(post)数据和文件

这两天因为工作的需要,需要做一个winform上传数据到服务器端的程序.当时第一个想法是通过webservice的方式来实现,后来觉得麻 烦,想偷懒就没有用这样的方式,http的post方式变成了第一选择.因为以前用的都是httpwebrequest之类的东西进行post提 交,winform下面还真的是第一次,不过很快就在网上找到了webclient这个类,接下来开始实现功能,话说webclient用起来还真的很简 单,一个头信息的声明,然后是URL,最后是post的数据,就完事了.正在高兴的

使用WebClient类对网页下载源码,对文件下载保存及异步下载并报告下载进度

private void button1_Click(object sender, EventArgs e) { WebClient webclient = new WebClient(); webclient.Proxy = null; webclient.Encoding = Encoding.UTF8; richTextBox1.AppendText(webclient.DownloadString(textBox1.Text.Trim())); webclient.Dispose();

怎么利用C#中的 webclient 创建cookie

Cookies are not limited only to web browsers. any http-aware client that supports cookies can deal with a cookie sending aSp .net Web api. the following code example shows a class extended from WebClient. it overrides the virtual method GetWebRequest

C# WebClient 实现上传下载网络资源

下载数据 WebClient wc = new WebClient();1 string str= wc.DownloadString("地址")://直接下载字符串 2 wc.DownloadFile("addredd", "fileName");//下载文件 并指定下载到的地址 3  byte[] b=wc.DownloadData("address")//直接返回一个二进制数组 然后进行转换 wc.Dispose();

如何基于Vert.x实现远程调用?

Vert.x的微服务 最近关于微服务的概念到处都在宣传,而Vert.x的verticle本身就是很好的一种服务定义,你可以把verticle看成一个service,也可以把verticle看成一个actor.这样你的视角会切到Actor模型里.本文我们将讨论如何基于Vert.x实现远程调用. 传统Java开发人员受EJB以及Spring的影响比较深,所以对面向接口编程了解的比较多.哪怕跨JVM也可以通过接口来调用对方提供的方法.这是非常友好方便的开发方式,因为框架层面做了服务发现以及服务生命周期

Vert.x入门教程

Vert.x是一个轻量级的高性能JVM应用平台,基于它可开发各种移动,Web和企业应用程序.一个主要特点是可使用多种语言编写应用,如Java, JavaScript, CoffeeScript, Ruby, Python 或 Groovy等等,它的简单actor-like机制能帮助脱离直接基于多线程编程.它是基于Netty和Java 7的NIO2的编写的. 当前业界遭遇C10K问题,当并发连接超过10,000+以上时使用传统技术会引发暂停,移动设备或视频 声音如类似微信这样的实时聊天,都是属于长