Android从URL下载pdf

时间:2014-06-24 23:42:08

标签: android pdf httprequest httpresponse android-download-manager

我正在尝试从URL中下载pdf,其中pdf是响应流的一部分,而不是将其作为响应的一部分附加。下面是我尝试的代码,但没有太多运气,因为当pdf被破坏,因为里面写了一些html内容。不确定问题出在哪里。

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();

任何帮助将不胜感激。谢谢。

1 个答案:

答案 0 :(得分: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