Search code examples
javaspringspring-bootmultipartform-dataspring-webclient

Spring Boot - WebClient - multipart response - How to get the binary data


Here is my code to call a REST-Service

 String result = webClient.post()
                .body(BodyInserters.fromMultipartData(bodyBuilder.build()))
                .exchangeToMono(clientResponse -> clientResponse.bodyToMono(String.class))
                .block();

This works fine. I get a HTTP-Status 200.

Response

Header Content-Type: multipart/form-data; boundary="n1OnMVB:z)VeTRs)kd9:h8Hz9H+_kywMV2mb)MWu."

Body

--n1OnMVB:z)VeTRs)kd9:h8Hz9H+_kywMV2mb)MWu. Content-Disposition: form-data; name="lastname"

smith
--n1OnMVB:z)VeTRs)kd9:h8Hz9H+_kywMV2mb)MWu. Content-Disposition: form-data; name="data"; filename="data.cms" Content-Transfer-Encoding: binary

0�  *�H�� ��0�

Problem/Question: How can i receive the binary data. I need something like that

byte[] result = webClient.post()....... -> clientResponse.bodyToMono(byte[])

Or even better

MyResultObject result = webClient.post().....-> clientResponse.bodyToMono(MyResultObject.class)

Where MyResultObject has the corresponding members.

I tried many. I searched a lot. But i found unfortunately nothing what helped me.


Solution

  • Finally i found a solution. I first tried it with RestTemplate. Same problem, i found no solution to access the binary data.

    I found a working solution without REST. I use httpClient directly.

     CloseableHttpResponse response = client.execute(httpPost);
     InputStream in = new BufferedInputStream(response.getEntity().getContent());
     ByteArrayDataSource datasource = new ByteArrayDataSource(in, "multipart/form-data");
     MimeMultipart multipartR = new MimeMultipart(datasource);
     BodyPart bodyPart = multipartR.getBodyPart(1); //Or you can iterate about the body parts
     InputStream is = bodyPart.getInputStream());