0

Я пытаюсь загрузить pdf-файл из 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

с вашим URL, попробуйте вставить его в свой браузер (чтобы начать загрузку) и посмотреть, действительно ли файл не поврежден ... – PinoyCoder