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

前端之家收集整理的这篇文章主要介绍了如何使用Android使用webView下载基于会话/ cookie的文件?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在尝试使用webView从文件主机(如zippyshare.com)下载文件.
问题是,我不能使用意图来打开浏览器,或者通过DownloadManager重新路由它,因为它是基于会话/ cookie的,并且启动这些方法会将z​​ip文件重定向到原始的html文件中以重新下载.

我试过了:

  1. Uri source = Uri.parse(url);
  2. DownloadManager.Request request = new DownloadManager.Request(source);
  3.  
  4. String cookie = CookieManager.getInstance().getCookie(url);
  5. request.addRequestHeader("Set-Cookie",cookie);
  6. request.addRequestHeader("User-Agent",view.getSettings().getUserAgentString());
  7. request.addRequestHeader("Accept","text/html,application/xhtml+xml,*" + "/" + "*");
  8. request.addRequestHeader("Accept-Language","en-US,en;q=0.7,he;q=0.3");
  9. request.addRequestHeader("Referer",url);
  10.  
  11. // Use the same file name for the destination
  12. final File destinationDir = new File (Environment.getExternalStorageDirectory(),cordova.getActivity().getPackageName());
  13.  
  14. if (!destinationDir.exists()) {
  15. destinationDir.mkdir(); // Don't forget to make the directory if it's not there
  16. }
  17.  
  18. File destinationFile = new File (destinationDir,source.getLastPathSegment());
  19. Log.e("FILEPOSITION",Uri.fromFile(destinationFile).toString());
  20. request.setDestinationUri(Uri.fromFile(destinationFile));
  21. // Add it to the manager
  22. manager.enqueue(request);

和:

  1. Bundle bundle = new Bundle();
  2.  
  3. String cookie = CookieManager.getInstance().getCookie(url);
  4. bundle.putString("cookie",cookie);
  5. bundle.putString("User-Agent",view.getSettings().getUserAgentString());
  6.  
  7. Intent intent = new Intent(Intent.ACTION_VIEW,Uri.parse(url));
  8. intent.putExtra(Browser.EXTRA_HEADERS,bundle);
  9. cordova.getActivity().startActivity(intent);

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

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

解决方法

我正在处理同样的问题,我设法让你的第一个解决方案工作,只是略有改变.只需替换Set-Cookie宽度Cookie:
  1. request.addRequestHeader("Cookie",cookie);

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

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

这是一个老问题,但我希望它会帮助某人.

猜你在找的Android相关文章