我正在尝试使用WebClient从客户端发送一个字节[]到服务器,这就是我所拥有的:
HttpClient httpClient = HttpClient.create();
// some proxy Settings to httpClient..
ReactorClientHttpConnector connector = new ReactorClientHttpConnector(httpClient);
WebClient client = WebClient.builder().clientConnector(connector).build();
MultipartBodyBuilder formDataBuilder = new MultipartBodyBuilder();
String header = String.format("form-data; pack=%s;", pack); // pack is byte[]
formDataBuilder.part("pack", new ByteArrayInputStream(pack)).header("Content-Disposition", header);
formDataBuilder.part("simpleParam", "testParam");
client.post().uri("myurl.test").accept(MediaType.APPLICATION_XML).contentType(MediaType.MULTIPART_FORM_DATA)
.header("Content-type", MediaType.MULTIPART_FORM_DATA_VALUE)
.body(BodyInserters.fromMultipartData(formDataBuilder.build()))
.retrieve()
.bodyToMono(Response.class)
.block();
执行这段代码,虽然我得到这个错误:
org.springframework.core.codec.CodecException: No suitable writer found for part: pack
at org.springframework.http.codec.multipart.MultipartHttpMessageWriter.encodePart(MultipartHttpMessageWriter.java:260)
at org.springframework.http.codec.multipart.MultipartHttpMessageWriter.lambda$encodePartValues$4(MultipartHttpMessageWriter.java:213)
....
我不明白少了什么。
任何帮助都是感激的,谢谢你
您的问题是您的Content-Disposition
标头无效。你不应该把你的byteArray放到header中。你可以在这里阅读更多关于Content-Disposition Header的信息
也在我的情况下,它帮助我通过一个ByteArrayResource
而不是ByteArrayInputStream
。我建议您尝试以下解决方案之一:
- 设置Content-Disposition Header正确:
// ...
String header = String.format("form-data; name=%s; filename=%s", "part", "testFilename.txt");
// ...
- 使用ByteArrayResource代替ByteArrayInputStream
formDataBuilder.part("pack", new ByteArrayResource(pack)).filename("testFilename.txt");