0

에서 pdf를 다운로드하려고합니다. 응답의 일부로 첨부하는 대신 응답 스트림의 일부인 URL에서 pdf를 다운로드하려고합니다. 아래에 코드를 시도했지만 거기에 많은 HTML 코드가 있기 때문에 pdf가 손상되면 많은 행운이 없습니다. 문제가있는 곳을 잘 모릅니다.URL 다운로드

URL url = new URL(fileURL); 
     HttpURLConnection httpConn = (HttpURLConnection) url.openConnection(); 
     int responseCode = httpConn.getResponseCode(); 
     // always check HTTP response code first 
     System.out.println("resp: "+responseCode); 
     if (responseCode == HttpURLConnection.HTTP_OK) { 
      String fileName = ""; 
      String disposition = httpConn.getHeaderField("Content-Disposition"); 
      String contentType = httpConn.getContentType(); 
      int contentLength = httpConn.getContentLength(); 
      if (disposition != null) { 
       // extracts file name from header field 
       int index = disposition.indexOf("filename="); 
       if (index > 0) { 
        fileName = disposition.substring(index + 10, 
          disposition.length() - 1); 
       } 
      } else { 
       // extracts file name from URL 
       fileName = fileURL.substring(fileURL.lastIndexOf("/") + 1, 
         fileURL.length()); 
      } 
      System.out.println("Content-Type = " + contentType); 
      System.out.println("Content-Disposition = " + disposition); 
      System.out.println("Content-Length = " + contentLength); 
      System.out.println("fileName = " + fileName); 
      // opens input stream from the HTTP connection 
      InputStream inputStream = httpConn.getInputStream(); 
      String saveFilePath = saveDir + File.separator + fileName; 
      // opens an output stream to save into file 
      FileOutputStream outputStream = new FileOutputStream(saveFilePath); 
      int bytesRead = -1; 
      byte[] buffer = new byte[1024*1024]; 
      while ((bytesRead = inputStream.read(buffer)) != -1) { 
       outputStream.write(buffer, 0, bytesRead); 
      } 
      outputStream.close(); 
      inputStream.close(); 

      System.out.println("File downloaded"); 
     } else { 
      System.out.println("No file to download. Server replied HTTP code: " + responseCode); 
     } 
     httpConn.disconnect(); 

어떤 도움을 주시면 감사하겠습니다. 고맙습니다.

+0

코드이 튜토리얼이 완전히 작동 확인 및 이해하기 쉽습니다. https://androidknowledgeblog.wordpress.com/2016/04/02/download-pdf-from-server-android/ –

답변

0

이 작업을 수행하려면 Apache's commons-io FileUtils.copyURLToFile (URL, java.io.File)을 사용합니다.

구현 예는 다음과 같습니다이 시점에서

File f = new File(Environment.getExternalStorageDirectory(), "foo.pdf"); 
URL url = new URL("https://foosite.com/files/foo.pdf"); 
FileUtils.copyURLToFile(new URL("http://foo"), f); 

, 당신의 파일 객체가 처리를위한 준비가 될 것입니다.

참조 : http://commons.apache.org/proper/commons-io/apidocs/org/apache/commons/io/FileUtils.html

+0

이 방법을 시도했습니다. pdf 파일이 여전히 손상되었습니다. : (URL이 – user3200361

+0

인 경우 브라우저에 붙여 넣어 다운로드를 시작하고 파일이 실제로 손상되지 않았는지 확인하십시오. – PinoyCoder