[英]Spring WebClient. Receive multipart/form-data
There is existing BodyExtractors
for multipart/form-data for using with WebClient.现有的用于多部分/表单数据的BodyExtractors
可与 WebClient 一起使用。
I found:我发现:
BodyExtractors.toMultipartData()
) ( BodyExtractors.toMultipartData()
)But I can't find the solution to parse multipart response body by WebClient.但是我找不到通过 WebClient 解析多部分响应正文的解决方案。
You must register it as a custom codec directly with the WebClient
.您必须直接使用WebClient
将其注册为自定义编解码器。
For example, in your WebClient bean:例如,在您的 WebClient bean 中:
return WebClient.builder()
.codecs(clientCodecConfigurer -> clientCodecConfigurer.defaultCodecs().maxInMemorySize(1 * 1024 * 1024)) // How to change defaults
.codecs(clientCodecConfigurer -> clientCodecConfigurer.customCodecs()
.register(new MultipartHttpMessageReader(new DefaultPartHttpMessageReader())) // <-- Add this custom codec
)
.defaultHeader(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE) // How to set default header
.baseUrl("https://foo.local") // How to set Base URL in builder
.build();
This registers the MultipartHttpMessageReader
for this WebClient
.这会为此WebClient
注册MultipartHttpMessageReader
。
If you only have a WebClient instance prefabricated, you can still mutate it:如果您只预制了一个 WebClient 实例,您仍然可以对其进行变异:
MultiValueMap<String, Part> response = webClient
.mutate() // This creates a pre-initialized builder
.codecs(clientCodecConfigurer -> clientCodecConfigurer.customCodecs()
.register(new MultipartHttpMessageReader(new DefaultPartHttpMessageReader())) // <-- Add our codec
)
.build() // Build a new instance
.get() // Whatever is your HTTP method
.accept(MediaType.MULTIPART_FORM_DATA)
.retrieve()
.bodyToMono(new ParameterizedTypeReference<MultiValueMap<String, Part>>() {
/* Freeze generic types. You need the exact type, as the Codec looks into the key and value types as well. */
})
.block();
This way, you can keep the values from the previous builder (eg, OAuth2 filters).这样,您可以保留来自先前构建器的值(例如,OAuth2 过滤器)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.