How to receive application/pdf response from a server using RestTemplate
Asked Answered
F

2

10

I am trying capture the response of an HTTP request made by my java client code. The response has a content-type of application/pdf. In the logs I can see that the server sent a response in

Object result = getRestTemplate().postForObject(urlString, formDataHttpEntity, returnClassObject, parametersMapStringString);

and I get the following JUnit error:

org.springframework.web.client.RestClientException: Could not extract response: no suitable HttpMessageConverter found for response type [java.lang.Object] and content type [application/pdf]

What do I need to do to get past this? My ultimate goal is to take this in a byte[] and push it in a DB table field of blob type

Note: I get the following response header from the server

HTTP/1.1 200 OK Cache-Control: max-age=0,must-revalidate
Content-Disposition: attachment; filename="Executive Summary.PDF"
Content-Type: application/pdf

Freeze answered 26/8, 2014 at 16:13 Comment(1)
docs.spring.io/spring-framework/docs/current/javadoc-api/org/… would be, what you are looking forTriumvirate
F
17

Thanks Thomas it worked.

I added ByteArrayHttpMessageConverter to the RestTemplate and it worked.

Code I added:

ByteArrayHttpMessageConverter byteArrayHttpMessageConverter = new ByteArrayHttpMessageConverter();

List<MediaType> supportedApplicationTypes = new ArrayList<>();
MediaType pdfApplication = new MediaType("application","pdf");
supportedApplicationTypes.add(pdfApplication);

byteArrayHttpMessageConverter.setSupportedMediaTypes(supportedApplicationTypes);
List<HttpMessageConverter<?>> messageConverters = new ArrayList<>();
messageConverters.add(byteArrayHttpMessageConverter);
restTemplate = new RestTemplate();
restTemplate.setMessageConverters(messageConverters);

Object result = getRestTemplate().getForObject(url, returnClass, parameters);
byte[] resultByteArr = (byte[])result;
Freeze answered 26/8, 2014 at 20:28 Comment(1)
You can replace by List<MediaType> supportedApplicationTypes = new ArrayList<>(); ... List<HttpMessageConverter<?>> messageConverters = new ArrayList<>();Shortfall
T
2

API I calling to get PDF is returning InputStreamResource. To get the response, I used it this way and I was able to get a successful byte array of pdf.

public byte[] callApiToGetPDF(Object  reqData) {
    
    String urlForEndPoint= baseUrl + "/" +    "";   
    HttpEntity<Object> entity = new HttpEntity<>(reqData, buildHeaders());
    return restTemplate.postForEntity(urlForEndPoint, entity, byte[].class).getBody();
}
Thrips answered 15/11, 2021 at 6:6 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.