【问题标题】:How to receive application/pdf response from a server using RestTemplate如何使用 RestTemplate 从服务器接收应用程序/pdf 响应
【发布时间】:2014-10-20 01:19:08
【问题描述】:

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

中发送了响应
Object result = getRestTemplate().postForObject(urlString, formDataHttpEntity, returnClassObject, parametersMapStringString);

我收到以下 JUnit 错误:

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

我需要做什么才能克服这个问题?我的最终目标是将其放入 byte[] 并将其推送到 blob 类型的数据库表字段中

注意:我从服务器得到以下响应头

HTTP/1.1 200 OK 缓存控制:max-age=0,must-revalidate
内容处置:附件; filename="执行摘要.PDF"
内容类型:application/pdf

【问题讨论】:

标签: java spring pdf resttemplate


【解决方案1】:

感谢托马斯,它成功了。

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

我添加的代码:

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;

【讨论】:

  • 您可以替换为 List supportedApplicationTypes = new ArrayList(); ... List> messageConverters = new ArrayList();
【解决方案2】:

我调用获取 PDF 的 API 返回 InputStreamResource。 为了得到响应,我用这种方式得到了一个成功的 pdf 字节数组。

public byte[] callApiToGetPDF(Object  reqData) {
    
    if (StringUtils.isEmpty(baseUrl)) {
        setRuntimeConfigurationValues();
    }
    
    String urlForEndPoint= baseUrl + "/" +    "";   
    HttpEntity<Object> entity = new HttpEntity<>(reqData, buildHeaders());
    return restTemplate.postForEntity(urlForEndPoint, entity, byte[].class).getBody();
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-26
    • 2012-05-05
    • 1970-01-01
    • 2018-02-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多