【问题标题】:How to write async data to remote endpoint without getting "No suitable writer found exception"?如何将异步数据写入远程端点而不会出现“未找到合适的写入器异常”?
【发布时间】:2019-09-20 21:48:09
【问题描述】:

我有以下控制器方法:

@PostMapping(consumes = MediaType.MULTIPART_FORM_DATA_VALUE, path = "/upload")
public Mono<SomeResponse> saveEnhanced(@RequestPart("file") Mono<FilePart> file) {
    return documentService.save(file);
}

调用服务方法,我尝试使用 WebClient 将一些数据放入另一个应用程序:

public Mono<SomeResponse> save(Mono<FilePart> file) {
    MultipartBodyBuilder bodyBuilder = new MultipartBodyBuilder();
    bodyBuilder.asyncPart("file", file, FilePart.class);
    bodyBuilder.part("identifiers", "some static content");
    return WebClient.create("some-url").put()
            .uri("/remote-path")
            .syncBody(bodyBuilder.build())
            .retrieve()
            .bodyToMono(SomeResponse.class);

}

但我得到了错误:

org.springframework.core.codec.CodecException: No suitable writer found for part: file

我尝试了 MultipartBodyBuilder 的所有变体(部分、异步部分、带或不带标头),但无法使其正常工作。

我是不是用错了,我错过了什么?

问候, 亚历克斯

【问题讨论】:

  • 您是否尝试将正确的内容类型标头添加到您的 WebClient HTTP 请求中? Spring 尝试默认将FilePart 序列化为 JSON 并失败。
  • 我终于发现了这个问题,它结合了 Spring 贡献者之一的响应和来自另一个来源的附加信息。我将其发布为答案。

标签: spring-boot spring-webflux


【解决方案1】:

在收到 Spring Framework Github 问题部分的其中一位贡献者的回复后,我找到了解决方案。 为此:

asyncPart 方法需要实际内容,即 file.content()。我会更新它以自动解开部分内容。

bodyBuilder.asyncPart("file", file.content(), DataBuffer.class)
    .headers(h -> {
        h.setContentDispositionFormData("file", file.name());
        h.setContentType(file.headers().getContentType());
    });

如果两个标头都没有设置,那么远程端的请求将失败,说它找不到表单部分。

祝所有需要这个的人好运!

【讨论】:

    猜你喜欢
    • 2017-05-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-28
    • 1970-01-01
    • 2018-11-23
    相关资源
    最近更新 更多