如何使用Android使用webView下载基于会话/ cookie的文件?

时间:2013-07-29 17:00:25

标签: android webview download downloading

我正在尝试使用webView从文件主机(如zippyshare.com)下载文件。 问题是,我不能使用意图来打开浏览器,或者通过DownloadManager重新路由它,因为它是基于会话/ cookie的,并且启动这些方法会将z​​ip文件重定向到原始的html文件中以重新下载。

我试过了:

Uri source = Uri.parse(url);
DownloadManager.Request request = new DownloadManager.Request(source);

String cookie = CookieManager.getInstance().getCookie(url);
request.addRequestHeader("Set-Cookie", cookie);
request.addRequestHeader("User-Agent", view.getSettings().getUserAgentString());
request.addRequestHeader("Accept", "text/html, application/xhtml+xml, *" + "/" + "*");
request.addRequestHeader("Accept-Language", "en-US,en;q=0.7,he;q=0.3");
request.addRequestHeader("Referer", url);

// Use the same file name for the destination
final File destinationDir = new File (Environment.getExternalStorageDirectory(), cordova.getActivity().getPackageName());

if (!destinationDir.exists()) {
    destinationDir.mkdir(); // Don't forget to make the directory if it's not there
}

File destinationFile = new File (destinationDir, source.getLastPathSegment());
Log.e("FILEPOSITION", Uri.fromFile(destinationFile).toString());
request.setDestinationUri(Uri.fromFile(destinationFile));
// Add it to the manager
manager.enqueue(request);

Bundle bundle = new Bundle();

String cookie = CookieManager.getInstance().getCookie(url);
bundle.putString("cookie", cookie);
bundle.putString("User-Agent", view.getSettings().getUserAgentString());

Intent intent = new Intent(Intent.ACTION_VIEW ,Uri.parse(url));
intent.putExtra(Browser.EXTRA_HEADERS, bundle);
cordova.getActivity().startActivity(intent);

尝试保留cookie,虽然我看到标题发送得很好,但它仍然会重定向到html链接,这让我相信它是基于会话的。

有没有办法以这种方式下载文件?

1 个答案:

答案 0 :(得分:6)

我正在处理同样的问题,我设法让你的第一个解决方案正常工作,只是略有改变。只需替换Set-Cookie宽度Cookie

request.addRequestHeader("Cookie", cookie);

顺便说一下。 基于会话意味着身份验证数据不存储在cookie中,而是存储在服务器端,由密钥标识,密钥存储在cookie中。因此,它是否基于会话实际上并不重要,在两种情况下都使用cookie。

我也尝试了第二种解决方案(它更简单),但从我所看到的情况来看,似乎只有默认的Android浏览器支持Browser.EXTRA_HEADERS。因此,如果用户的设备中有不同的浏览器,则无法使用。

这是一个老问题,但我希望它会对某人有所帮助。