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());
}
});  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM