简体   繁体   中英

How to consume binary and String Response using WebClient in Spring boot?

I need to consume a vendor API which returns file(.pdf/.jpg/.png) in binary format when request succeeds while returns a JSON Response when Request fails. The Request method is of type POST.
I tried using below code:

  WebClient webClient = WebClient.create();
  ResponseEntity<Object> apiResponse = webClient.post()
                .uri(new URI("https://api.myapp.in/getDocument"))
                .header("mobile", "XXXXXXXXX8")
                .contentType(MediaType.APPLICATION_FORM_URLENCODED)
                //.accept(MediaType.parseMediaType("application/pdf"))
                .body(BodyInserters.fromFormData(map))
                .retrieve()
                .toEntity(Object.class)
                .block();

When i execute the above code it works fine and i am able to get the JSON Response for Error case but when the request is success it gives error as below:

 Content type 'application/pdf' not supported

Once your get Response, you can ResponseEntity.getHeaders() .

From the response headers you can get the content type and consume your response accordingly. If API does not return valid content-type based on the response, you can raise a defect on the API provider.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM