簡體   English   中英

Spring 引導 - WebClient - 多部分響應 - 如何獲取二進制數據

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

這是我調用 REST 服務的代碼

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

這很好用。 我收到 HTTP-Status 200。

回復

Header 內容類型:多部分/表單數據; boundary="n1OnMVB:z)VeTRs)kd9:h8Hz9H+_kywMV2mb)MWu。"

身體

--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�

問題/問題:我如何接收二進制數據。 我需要那樣的東西

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

甚至更好

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

其中 MyResultObject 有相應的成員。

我試了很多。 我搜索了很多。 但不幸的是,我沒有發現任何幫助我的東西。

最后我找到了解決方案。 我第一次嘗試使用 RestTemplate。 同樣的問題,我沒有找到訪問二進制數據的解決方案。

我找到了一個沒有 REST 的工作解決方案。 我直接使用httpClient。

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

現在有一種方法可以通過Spring Flux webclient 並使用DefaultPartHttpMessageReader class

首先我們需要讀者

final var partReader = new DefaultPartHttpMessageReader();
partReader.setStreaming(false); 

然后通過weblcient撥打電話

WebClient webClient = WebClient.builder().build();
ResponseEntity<Flux<Part>> request = webClient
                .get()
                .uri("...")
                .accept(MediaType.MULTIPART_MIXED)
                .retrieve()
                .toEntityFlux((inputMessage, context) ->
                        partReader
                                .read(ResolvableType.forType(byte[].class), inputMessage, Map.of()))
                .block();

執行請求后,我們將獲得Flux<Part>作為響應,每個部分都是多部分響應的各個部分。

part.headers()將為您提供標題,而part.content()將為您提供DataBuffer格式的實際內容。 例如,如果你想從響應中提取圖像並以字節為單位發送,你可以這樣做:

            byte[] image = null;
    
            List<Part> parts = request.getBody().collectList().block();
    
            for (Part part : parts) {
                // access individual parts here
                System.out.println(part.headers());
                if (part.headers().get("Content-Type").get(0).equals("image/jpeg")) {
                    image = DataBufferUtils.join(part.content())
                            .map(dataBuffer -> {
                                byte[] bytes = new byte[dataBuffer.readableByteCount()];
                                dataBuffer.read(bytes);
                                DataBufferUtils.release(dataBuffer);
                                return bytes;
                            }).block();
                }
            }
return image;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM