如果你想发送json体请求,使用sendJsonObject发送JsonObject
client
.post(8080, "myserver.mycompany.com", "/some-uri")
.sendJsonObject(
new JsonObject()
.put("firstName", "Dale")
.put("lastName", "Cooper"))
.onSuccess(res -> {
// OK
});
在Java Groovy,或者Kotlin可以使用sendJson方法中可以使用Json.encode将PoJO转成Json
client
.post(8080, "myserver.mycompany.com", "/some-uri")
.sendJson(new User("Dale", "Cooper"))
.onSuccess(res -> {
// OK
});
注意:
Json.encode方法使用Jackson Mapper去将对象转成Json
你可以使用sendForm方法发送http表单请求
MultiMap form = MultiMap.caseInsensitiveMultiMap();
form.set("firstName", "Dale");
form.set("lastName", "Cooper");
// Submit the form as a form URL encoded body
client
.post(8080, "myserver.mycompany.com", "/some-uri")
.sendForm(form)
.onSuccess(res -> {
// OK
});
表单默认使用application/x-www-form-urlencoded内容格式头。你可以设置content-type头的值为multipart/form-data作为替代方案
MultiMap form = MultiMap.caseInsensitiveMultiMap();
form.set("firstName", "Dale");
form.set("lastName", "Cooper");
// Submit the form as a multipart form body
client
.post(8080, "myserver.mycompany.com", "/some-uri")
.putHeader("content-type", "multipart/form-data")
.sendForm(form)
.onSuccess(res -> {
// OK
});
如是你想上传文件并上传属性,可以用sendMultipartForm方法发送MultipartForm实例
MultipartForm form = MultipartForm.create()
.attribute("imageDescription", "a very nice image")
.binaryFileUpload(
"imageFile",
"image.jpg",
"/path/to/image",
"image/jpeg");
// Submit the form as a multipart form body
client
.post(8080, "myserver.mycompany.com", "/some-uri")
.sendMultipartForm(form)
.onSuccess(res -> {
// OK
});
可以使用multi-map向请求添加请求头
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");
请求头是MultiMap实例,MultiMap提供了添,设置,和移除头的方法。一个Http请求头允许指定更多值
也可以使用putHeader方法设置头
HttpRequest<Buffer> request = client
.get(8080, "myserver.mycompany.com", "/some-uri");
request.putHeader("content-type", "application/json");
request.putHeader("other-header", "foo");
通过设置正确的请,认证可以手工设置,或者使用预定义的方法(我们强列推荐使用HTTPS,特别是认证请求):
在Basic Http认证中,一个请求中保含表单头字段:Authorization:Basic <credentials>,id和密码字段采用Base64编码并用:号进行分隔
可用以下方法配置basic 访问认证请求
HttpRequest<Buffer> request = client
.get(8080, "myserver.mycompany.com", "/some-uri")
.authentication(new UsernamePasswordCredentials("myid", "mypassword"));
在OAuth 2.0,一个请求中包含表单请求头Authorization:Bearer <bearerToken>, bearerToken是认证服务器分发的持票人Token用来保护资源的访问。
你可以用以下方法来添加token使用OAuth 2.0请求
HttpRequest<Buffer> request = client
.get(8080, "myserver.mycompany.com", "/some-uri")
.authentication(new TokenCredentials("myBearerToken"));