java 使用Spring RestTemplate和Basic Auth和Custom header发送PDF附件

kdfy810k  于 2023-10-14  发布在  Java
关注(0)|答案(3)|浏览(99)

我需要使用PUT发送一个PDF附件,就像你在POSTMAN POSTMAN EXAMPLE中附加文档一样。我使用的服务将只接受请求正文中的PDF文件。
下面是我的代码:

// create new file
FileSystemResource file = new FileSystemResource(new File("/Users/name/Documents/test.pdf"));
MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
body.add("file", file);

// adding basic auth
HttpHeaders headers = createHeaders(username, password);
// required custom header
headers.set("X-Async-Scope", timelineEntryId);
HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(body, headers);

RestTemplate restTemplate = new RestTemplate();
ResponseEntity<String> response = restTemplate.exchange(baseUrl, HttpMethod.PUT, requestEntity, String.class);

问题是响应带有状态代码415不支持的媒体类型,我不知道为什么。我的HttpEntity主体格式不对吗?

kkbh8khc

kkbh8khc1#

我遇到了另一个解决方案,帮助了我很多!different solution这里是我的最终代码和解决我自己的问题。

HttpHeaders headers = createHeaders(username, password);
headers.setContentType(MediaType.APPLICATION_PDF);
headers.set("X-Async-Scope", timelineEntryId);

InputStream inputStream = new FileSystemResource(new File(file.getPath())).getInputStream();
byte[] binaryData = IOUtils.toByteArray(inputStream);
HttpEntity<byte[]> requestEntity = new HttpEntity<>(binaryData, headers);

RestTemplate restTemplate = new RestTemplate();
ResponseEntity<String> response = restTemplate.exchange(baseUrl, HttpMethod.PUT, requestEntity, String.class);
w6lpcovy

w6lpcovy2#

也许,你需要设置标题内容类型?

headers.set("Content-Type", "application/pdf")

如果没有帮助,你还应该设置头Content-Disposition:

headers.set("Content-Disposition", "attachment; filename="+fileName)
xtfmy6hx

xtfmy6hx3#

你可以试穿

String headerKey = "Content-Disposition";
        String headerValue = "attachment; filename=category_list"  + ".xlsx";
        response.setHeader(headerKey, headerValue);

        categoryServiceImpl.exportToExcelFile(response);

相关问题