【问题标题】:WebResource multipart post requestWebResource 多部分发布请求
【发布时间】:2016-05-22 07:53:09
【问题描述】:

我需要使用 java 测试向这个 rest 函数发送 post 请求:

@RequestMapping(value = "/upload", method = RequestMethod.POST)
public @ResponseBody String handleFileUpload(@PathVariable Long ownerId, @RequestBody MultipartFile file,
        HttpServletResponse response) throws IOException {
//Some function
}

这是我的试验:

File file = new File("filePath");
FileDataBodyPart fileDataBodyPart = new FileDataBodyPart("file", file, MediaType.MULTIPART_FORM_DATA_TYPE);
WebResource webResource = createResourceClient("restPath", user);
ClientResponse response = webResource.type(MediaType.MULTIPART_FORM_DATA_TYPE).post(ClientResponse.class, fileDataBodyPart);

错误提示:

“当前请求不是多部分请求”

【问题讨论】:

  • 我没有测试过,但我不确定你是否可以自己发送FileDataBodyPart。您可能需要将其包装在 MultiPart 中。有关我的意思的示例,请参见 this post
  • 非常感谢它有效:))

标签: java rest multipartform-data httpwebresponse clienthttprequest


【解决方案1】:

以下代码会将文件和 ContentDispostion 发送到 REST API。

FormDataBodyPart formPart = new FormDataBodyPart(FormDataContentDisposition.name("file").fileName("YourFileName").build(),
            inputStream,MediaType.APPLICATION_OCTET_STREAM_TYPE);

    MultiPart multipart = new FormDataMultiPart().bodyPart(formPart);
    resource = resource.path("Your Rest api path");
ClientResponse response = resource.type(MediaType.MULTIPART_FORM_DATA).post(ClientResponse.class, multipart);

【讨论】:

    猜你喜欢
    • 2011-01-02
    • 2016-11-11
    • 1970-01-01
    • 2021-03-23
    • 2014-05-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-26
    相关资源
    最近更新 更多