我有一个PDF资源的URL,但它没有用它的文件名标识。请求如下所示:
<option *ngFor = "let paquete of paquetes">{{ paquete.nombre}} / {{ paquete.precio | currency}}</option>
响应是:
GET /api/docs/12345
Accept: application/pdf
当我使用Postman调用api时,它会提示使用默认文件名&#34; response&#34;保存文件。因此,文件保存为&#34; response.pdf&#34;。我需要使用RestTemplate客户端以编程方式执行此操作。我如何捕获响应,因此我可以提取文件名(如上面的响应,它是sample.pdf),我可以相应地保存文件而不是通用文件名,如&#34; response.pdf&#34; < / p>
答案 0 :(得分:1)
RestTemplate restTemplate = new RestTemplate();
restTemplate.getMessageConverters().add(new ByteArrayHttpMessageConverter());
HttpHeaders headers = new HttpHeaders();
//headers.add("Authorization", "Bearer SOME_BEARER_TOKEN"); //if requires some token
headers.setAccept(Arrays.asList(MediaType.APPLICATION_PDF));
HttpEntity<String> entity = new HttpEntity<>(headers);
try {
ResponseEntity<Resource> response = restTemplate.exchange(
"https://SOME_API.COM/api/docs/12345",
HttpMethod.GET, entity, Resource.class);
if (response.getStatusCode() == HttpStatus.OK) {
String disposition = response.getHeaders().get("Content-Disposition").get(0);
String fileName = disposition.replaceFirst("(?i)^.*filename=\"?([^\"]+)\"?.*$", "$1");//get the filename from the Content-Disposition header
fileName = URLDecoder.decode(fileName, String.valueOf(StandardCharsets.ISO_8859_1));
//save to examine file
File targetFile = new File("c:/temp/" + fileName);
FileUtils.copyInputStreamToFile(response.getBody().getInputStream(), targetFile);
}
} catch (RestClientException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
答案 1 :(得分:1)
使用spring boot可以通过以下方式获取文件名:
response.getHeaders().getContentDisposition().getFilename()
在以下情况下:
public void retrieveFile() {
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Arrays.asList(MediaType.APPLICATION_OCTET_STREAM));
HttpEntity<String> entity = new HttpEntity<>(headers);
ResponseEntity<byte[]> response = restTemplate.exchange(Url, HttpMethod.GET, entity, byte[].class, "1");
if(response.getStatusCode().equals(HttpStatus.OK))
{
byte[] scenarioBytesFile = response.getBody();
String fileName = response.getHeaders().getContentDisposition().getFilename();
// Do Someting with your file and name
}
}