【问题标题】:Vertx POST HttpClientRequest with body parameterVertx POST HttpClientRequest 与 body 参数
【发布时间】:2017-08-05 01:06:53
【问题描述】:

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

棘手的部分是服务器需要正文的密钥“upgrade_file”。我不知道如何用 Vertx 做到这一点。这是我目前所拥有的:

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

如何将“upgrade_file”设置为正文的键?

【问题讨论】:

标签: vert.x vertx-httpclient


【解决方案1】:

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

WebClient client = WebClient.create(vertx);

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

WebClient client = WebClient.wrap(httpClient);

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

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/

【讨论】:

    【解决方案2】:

    如果要发送文件,最简单的方法是使用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。然后将缓冲区发送到服务器端。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-04-01
      • 2022-06-14
      • 2018-04-05
      • 2021-02-15
      • 1970-01-01
      • 2022-12-03
      • 1970-01-01
      相关资源
      最近更新 更多