0

我試圖從URL下載pdf格式的應答流,而不是將其附加爲響應的一部分。下面是我嘗試過的代碼,但沒有太多的運氣,因爲當pdf因內部寫入一些html內容而被損壞時。不確定問題出在哪裏。Android下載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); 

在這一點上,你的File對象將準備進行處理。

參考: http://commons.apache.org/proper/commons-io/apidocs/org/apache/commons/io/FileUtils.html

+0

我試過這種方法。該pdf文件仍然是腐敗的。 :( – user3200361

+0

與您的網址,嘗試粘貼到您的瀏覽器(開始下載),看看文件是否真的沒有損壞... – PinoyCoder