下载PDF文件

时间:2011-12-05 11:27:35

标签: android pdf

在我的应用程序中,用户需要从URL下载PDF文件并将其存储在SD卡上。 但是这里的问题是我只能使用DefaultHttpClient来访问url。 我找到了几个解决方案但没有使用DefaultHttpClient。 下载PDF后,我还可以在我的应用程序中查看PDF。

3 个答案:

答案 0 :(得分:4)

//使用此方法下载pdf文件

 public void downloadPdfContent(String urlToDownload){

             try {

                 String fileName="xyz";
             String fileExtension=".pdf";

//           download pdf file.

                URL url = new URL(urlToDownload);
                HttpURLConnection c = (HttpURLConnection) url.openConnection();
                c.setRequestMethod("GET");
                c.setDoOutput(true);
                c.connect();
                String PATH = Environment.getExternalStorageDirectory() + "/mydownload/";
                File file = new File(PATH);
                file.mkdirs();
                File outputFile = new File(file, fileName+fileExtension);
                FileOutputStream fos = new FileOutputStream(outputFile);
                InputStream is = c.getInputStream();
                byte[] buffer = new byte[1024];
                int len1 = 0;
                while ((len1 = is.read(buffer)) != -1) {
                    fos.write(buffer, 0, len1);
                }
                fos.close();
                is.close();

               System.out.println("--pdf downloaded--ok--"+urlToDownload);
            } catch (Exception e) {
                e.printStackTrace();

            }
    }

//查看pdf使用此方法

private void onPdfClick()
    {

//      String pdfFile = Environment.getExternalStorageDirectory()+ File.separator + AstroManager.file.getName();

         Intent intent = new Intent(Intent.ACTION_VIEW);
         intent.setDataAndType(Uri.fromFile(new File("/sdcard/mydownload/xyz.pdf"), "application/*");

         startActivity(intent);
    }

答案 1 :(得分:1)

如果您必须打开pdf文件,必须在您的设备中安装pdf阅读器。否则它将显示空白屏幕。 另外here从服务器下载pdf 查看其内容的好例子。

答案 2 :(得分:0)

请参阅http://developer.android.com/reference/org/apache/http/client/methods/HttpGet.html,以便使用DefaultHttpClient

从网址中检索数据
相关问题