java 如何使用 RestTemplate 从服务器接收应用程序/pdf 响应

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25510498/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 08:09:19  来源:igfitidea点击:

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

javaspringpdfresttemplate

提问by aayushkr

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

我正在尝试捕获由我的 java 客户端代码发出的 HTTP 请求的响应。响应的内容类型为application/pdf。在日志中,我可以看到服务器在

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

and I get the following JUnit error:

我收到以下 JUnit 错误:

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

org.springframework.web.client.RestClientException:无法提取响应:没有找到适合响应类型 [java.lang.Object] 和内容类型 [application/pdf] 的 HttpMessageConverter

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

我需要做什么才能度过难关?我的最终目标是将其放入 abyte[]并将其推送到blob 类型的数据库表字段中

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

HTTP/1.1 200 OK Cache-Control: max-age=0,must-revalidate
Content-Disposition:attachment; filename="Executive Summary.PDF"
内容类型:应用程序/pdf

回答by aayushkr

Thanks Thomas it worked.

谢谢托马斯,它奏效了。

I added ByteArrayHttpMessageConverter to the RestTemplate and it worked.

我将 ByteArrayHttpMessageConverter 添加到 RestTemplate 并且它起作用了。

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;