我有一个 Android 应用程序,它使用单个 WebView,在其中加载一个网站。
setContentView(R.layout.activity_main);
WebView webView = (WebView) this.findViewById(R.id.webview);
Run Code Online (Sandbox Code Playgroud)
然后我使用下载管理器从服务器下载我的文件
webView.setDownloadListener(new DownloadListener() {
public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
// ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_CODE);
//for downloading directly through download manager
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
request.allowScanningByMediaScanner();
Environment.getExternalStorageDirectory();
getApplicationContext().getFilesDir().getPath(); //which returns the internal app files directory path
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "download");
DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
dm.enqueue(request);
}
});
Run Code Online (Sandbox Code Playgroud)
当我尝试下载由网站动态创建的文件时,我会下载网站 HTML 而不是 PDF。
webView.loadUrl("http://bookboon.com/");
Run Code Online (Sandbox Code Playgroud)
提前致谢
实际上该 HTML 页面显示的是用于身份验证的登录页面。因此,您需要一个位于该网站 cookie 内的会话密钥。
所以需要在onDownloadListener中添加三行
webView.setDownloadListener(new DownloadListener() {
public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
// ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_CODE);
//for downloading directly through download manager
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
//This three lines will do your work
CookieManager cookieManager = CookieManager.getInstance();
String cookie = cookieManager.getCookie("<Your website url>"); // which is "http://bookboon.com"
request.addRequestHeader("Cookie", cookie);
//................................................
request.allowScanningByMediaScanner();
Environment.getExternalStorageDirectory();
getApplicationContext().getFilesDir().getPath(); //which returns the internal app files directory path
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "download");
DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
dm.enqueue(request);
}
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7171 次 |
| 最近记录: |