2017-11-07 1 views
-1

PDF 자원에 대한 URL이 있지만 파일 이름으로 식별되지 않습니다.PDF 파일을 다운로드하고 파일 이름을 캡처하십시오.

GET /api/docs/12345 
Accept: application/pdf 

을 그리고 응답은 다음과 같습니다 : 요청은 다음과 같습니다

Status: 200 OK 
Content-Type: application/pdf 
Content-Disposition: attachment; filename="sample.pdf" 

나는 우체부와 API를 호출 할 때, "응답"의 기본 파일 이름으로 파일을 저장하라는 메시지가 표시됩니다. 따라서 파일은 "response.pdf"로 저장됩니다. RestTemplate 클라이언트를 사용하여 프로그래밍 방식으로이 작업을 수행해야합니다. 응답을 캡처하여 파일 이름을 추출 할 수 있습니다 (예 : 위의 응답에서와 같이 sample.pdf). 따라서 파일을 "response.pdf"와 같은 일반 파일 이름이 아닌 저장할 수 있습니다.

답변

0
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(); 
    } 
관련 문제