我正在尝试使用webview从文件主机(如zippyshare.com)下载一个文件。
问题是,我不能使用意图打开浏览器,也不能通过downloadmanager重新路由,因为它是基于会话/cookie的,启动这些方法会将zip文件重定向到原始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链接,这使我相信它是基于会话的。
有没有这样下载文件的方法?

最佳答案

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

request.addRequestHeader("Cookie", cookie);

顺便说一下,基于会话意味着身份验证数据不是存储在cookies中,而是存储在服务器端,由存储在cookies中的密钥标识。所以不管它是否基于会话,cookies在这两种情况下都会被使用。
我也尝试过第二种解决方案(它更简单),但从我所读到的内容来看,似乎只有默认的android浏览器支持Browser.EXTRA_HEADERS。因此,如果用户的设备中有不同的浏览器,它将无法工作。
这是个老问题,但我希望它能帮助别人。

07-28 01:50
查看更多