Send byteArray with WebClient

Viewed 249

I'm trying to send a byte[] from a client to a server using WebClient, this is what I have:

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();

Executing this code though i get this error:

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)
....

I don't understand what is missing.

Any help is appreciated, thank you

1 Answers

Your problem is that your Content-Disposition header is invalid. You shouldn't put your byteArray into the header. You can read more about Content-Disposition Header here

Also in my case it helps me to pass a ByteArrayResource instead of ByteArrayInputStream. I would recommend you to try one of these solutions:

  1. Set Content-Disposition Header correct:
// ...
String header = String.format("form-data; name=%s; filename=%s", "part", "testFilename.txt");
// ...
  1. Use ByteArrayResource instead of ByteArrayInputStream
formDataBuilder.part("pack", new ByteArrayResource(pack)).filename("testFilename.txt");
Related