【问题标题】:Android Download and Open PDF File from URL ending with .aspxAndroid 从以 .aspx 结尾的 URL 下载并打开 PDF 文件
【发布时间】:2017-07-24 23:43:30
【问题描述】:

我可以使用以下代码从以 *.pdf 结尾的 url 下载和查看

 private static final int  MEGABYTE = 1024 * 1024;

public static void downloadFile(String fileUrl, File directory){
    try {

        URL url = new URL(fileUrl);
        HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection();
        //urlConnection.setRequestMethod("GET");
        //urlConnection.setDoOutput(true);
        urlConnection.connect();

        InputStream inputStream = urlConnection.getInputStream();
        FileOutputStream fileOutputStream = new FileOutputStream(directory);
        int totalSize = urlConnection.getContentLength();

        byte[] buffer = new byte[MEGABYTE];
        int bufferLength = 0;
        while((bufferLength = inputStream.read(buffer))>0 ){
            fileOutputStream.write(buffer, 0, bufferLength);
        }
        fileOutputStream.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

但我尝试下载 url 以 .aspx 结尾的 PDF 文件,因为它会动态生成 PDF 并且无法正常工作。

我也尝试使用 google doc url "http://docs.google.com/viewer?url="+URL 嵌入 webview,但它也不起作用。

有人可以帮忙吗?

【问题讨论】:

    标签: android asp.net pdf android-webview pdf-viewer


    【解决方案1】:

    '.aspx' 是 ASP.NET 页面,实际上是 web 表单。

    Web 表单包含在扩展名为“.aspx”的文件中;这些文件 通常包含静态 (X)HTML 标记或组件标记。

    因此,您正在加载的是在服务器端呈现的简单 HTML 页面。所以你不能用它来查看PDF - 在PDF查看器中。

    不要从文件中打开“.aspx”,而是将此 url 加载到WebView - 只有在您指向的站点上没有额外的安全性时,这才有效。

    如果是 Google Docs,您提供给 WebView 的链接应该是共享链接,如下所示:

    https://drive.google.com/file/d/xx-xxxxxxxxxxxxxxx/view?usp=sharing

    x 是哈希的一部分。要获取此链接 - 单击文档的 Share 选项,然后单击 get shareable link

    WebView 到达 pdf 文档之前,它可能会收到一些可能由 Android 本身处理的重定向。为避免这种情况,您需要覆盖WebViewClient#shouldOverrideUrlLoading,如下例所示:

    mWebView.getSettings().setJavaScriptEnabled(true);
    
    mWebView.setWebViewClient(new WebViewClient() {
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            view.loadUrl(url);
            return false;
        }
    });
    mWebView.loadUrl("https://drive.google.com/file/d/xx-xxxxxxxxxxxxxxx/view?usp=sharing");
    

    您还可以使用上面获得的可共享网址直接链接到该文件:

    change this:
      https://drive.google.com/file/d/xx-xxxxxxxxxxxxxxx/view?usp=sharing
    to this:
      https://drive.google.com/uc?export=download&id=xx-xxxxxxxxxxxxxxx
    or to this:
      https://docs.google.com/document/d/xx-xxxxxxxxxxxxxxx/export?format=pdf
    

    【讨论】:

    • 我已经尝试了以上所有的 URL,但它不起作用。
    • HTML中的数据是动态生成并嵌入HTML中的blob数据
    • 请提供您使用过的真实链接,以便我正确回答您的问题
    猜你喜欢
    • 1970-01-01
    • 2017-03-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-01
    • 2014-09-04
    • 1970-01-01
    相关资源
    最近更新 更多