[英]Android Download and Open PDF File from URL ending with .aspx
我可以使用以下代码从以* .pdf结尾的网址下载和查看
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();
}
}
但是我试图下载以.aspx结尾的URL的PDF文件,因为它会动态生成PDF,并且无法正常工作。
我也尝试过使用带有Google doc url“ http://docs.google.com/viewer?url= ” + URL的webview嵌入,但是它也无法正常工作。
有人可以帮忙吗?
“ .aspx”是实际上是Web表单的ASP.NET页。
Web表单包含在扩展名为“ .aspx”的文件中; 这些文件通常包含静态(X)HTML标记或组件标记。
因此,您正在加载的是在服务器端呈现的简单HTML
页面。 因此,您不能使用它在PDF查看器中查看PDF
。
无需从文件中打开“ .aspx”,而是将该URL加载到WebView
-仅当您指向的站点上没有其他安全性时,此URL才起作用。
对于Google文档,您提供给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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.