使用带有基本身份验证和自定义标头的 Spring RestTemplate 发送 PDF 附件

我需要使用 PUT 发送 PDF 附件,就像您在 POSTMAN POSTMAN Examples中附加文档一样。我正在使用的服务仅接受请求正文中的 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 Unsupported Media Type,我不知道为什么。我的 HttpEntity 正文格式错误吗?


芜湖不芜
浏览 89回答 3
3回答

MYYA

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);

动漫人物

也许,您需要设置标题内容类型?headers.set("Content-Type",&nbsp;"application/pdf")如果没有帮助,您还应该设置标头 Content-Disposition:headers.set("Content-Disposition",&nbsp;"attachment;&nbsp;filename="+fileName)

PIPIONE

你可以试穿&nbsp; String headerKey = "Content-Disposition";&nbsp; &nbsp; &nbsp; &nbsp; String headerValue = "attachment; filename=category_list"&nbsp; + ".xlsx";&nbsp; &nbsp; &nbsp; &nbsp; response.setHeader(headerKey, headerValue);&nbsp; &nbsp; &nbsp; &nbsp; categoryServiceImpl.exportToExcelFile(response);
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java