如何从android中的特定URL打开pdf

时间:2013-07-30 18:01:12

标签: android html

我是一名iOS开发人员,但我也负责更新我们公司的Android应用程序(所以我的安卓体验很少)Android应用程序目前从raw加载PDF,然后在另一个安装在android上的pdf阅读器应用程序中显示它们。 ..但我想从互联网上获取pdf。

这是用于显示本地存储的pdf的代码。

          if (mExternalStorageAvailable==true && mExternalStorageWriteable==true)
      {
        // Create a path where we will place our private file on external
            // storage.
            Context context1 = getApplicationContext();
            File file = new File(context1.getExternalFilesDir(null).toString() + "/pdf.pdf");

            URL url = new URL("https://myurl/pdf.pdf");
            URLConnection urlConnection = url.openConnection();
            InputStream in = new BufferedInputStream(urlConnection.getInputStream());
            OutputStream os = new FileOutputStream(file);
            try {


                byte[] data = new byte[in.available()];
                in.read(data);
                os.write(data);




                Uri path = Uri.fromFile(file);
                Intent intent = new Intent(Intent.ACTION_VIEW);
                intent.setDataAndType(path, "application/pdf");
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

                startActivity(intent);

            } catch (IOException e) {
                // Unable to create file, likely because external storage is
                // not currently mounted.
                Log.w("ExternalStorage", "Error writing " + file, e);


                Context context2 = getApplicationContext();
                CharSequence text1 = "PDF File NOT Saved";
                int duration1 = Toast.LENGTH_SHORT;
                  Toast toast = Toast.makeText(context2, text1, duration1);
                  toast.show();
            } finally {
                 in.close();
                 os.close();
            }

      }

最终,pdf将来自一个网站,该网站将要求在下载PDF之前向其发送HTML帖子请求。我想我将能够弄清楚HTML帖子,但是现在如何从互联网上下载PDF并显示它。我尝试将URI更改为指向该位置,但这不起作用,或者我的结构不正确。

另外请注意出于安全原因,我不想使用Google查看器和网页浏览来显示此内容

1 个答案:

答案 0 :(得分:1)

您只需要从远程服务器读取即可。我会尝试类似的事情:

URL url = new URL("http://www.mydomain.com/slug");
URLConnection urlConnection = url.openConnection();
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
try {
    readStream(in); // Process your pdf
} finally {
    in.close();
}

您可能还想查看AndroidHttpClient课程以直接发出http请求(在您的应用程序中获取GET或POST)。