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

|▌冷眼眸甩不掉的悲伤 提交于 2020-02-20 08:17:06

问题


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


回答1:


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>();
MediaType pdfApplication = new MediaType("application","pdf");
supportedApplicationTypes.add(pdfApplication);

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

Object result = getRestTemplate().getForObject(url, returnClass, parameters);
byte[] resultByteArr = (byte[])result;


来源:https://stackoverflow.com/questions/25510498/how-to-receive-application-pdf-response-from-a-server-using-resttemplate

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!