带有body参数的Vertx POST HttpClientRequest

时间:2017-03-14 15:39:56

标签: vert.x vertx-httpclient

我必须实现Vertx POST请求。通过Postman,请求如下图所示:

enter image description here

棘手的部分是服务器需要密钥" upgrade_file"对于身体。我无法找到如何使用Vertx做到这一点。这就是我到目前为止所做的:

Buffer bodyBuffer = Buffer.buffer(body); // body is byte[]
HttpClientRequest request = ...
request.handler( response -> ...
request.end(bodyBuffer);

如何设置" upgrade_file"作为身体的关键?

2 个答案:

答案 0 :(得分:0)

使用WebClient代替HTTP客户端,它为提交表单提供专门支持。

WebClient client = WebClient.create(vertx);

或者如果您已经创建了http客户端:

WebClient client = WebClient.wrap(httpClient);

然后将表单数据创建为map,并使用正确的内容类型发送表单

MultiMap form = MultiMap.caseInsensitiveMultiMap();
form.set("upgrade_file", "...");

// Submit the form as a multipart form body
client.post(8080, "yourhost", "/some_address")
      .putHeader("content-type", "multipart/form-data")
      .sendForm(form, ar -> {
        //do something with the response
      });

更多示例请参阅https://vertx.io/docs/vertx-web-client/java/

答案 1 :(得分:0)

如果您想发送文件,最简单的方法是使用 Vertx WebClientsendMultipartForm 方法。

首先创建一个 Multipartform

MultipartForm form = MultipartForm.create()
  .attribute("imageDescription", "a very nice image")
  .binaryFileUpload(
    "imageFile",
    "image.jpg",
    "/path/to/image",
    "image/jpeg");

然后调用 WebClient.sendMultipartForm(form) 发送请求。

通用的 Vertx HttpClient 是一个低级 API,您应该将表单数据序列化为字符串或缓冲区,格式类似于 this example file in Vertx GraphQL testing codes。然后将缓冲区发送到服务器端。

相关问题