![](/img/trans.png)
[英]flutter_inappwebview and flutter_downloader - not sure what I'm doing wrong?
[英]Using flutter_downloader with flutter_inappwebview - Response with redirection code
我的 Flutter 应用程序允许用户访问需要通过 Flutter InAppWebView进行身份验证的网页。 该网页允许经过身份验证的用户下载 PDF 文件,因此我在 InAppWebView 的 onDownloadStart 事件中使用FlutterDownloader处理下载。
当我登录网页后尝试下载文件时,应用程序下载的是网站的索引页面,而不是 PDF 文件。 检查调试日志显示 URL 被重定向到登录 URL:
D/DownloadWorker(15942): Open connection to [PDF URL]
D/DownloadWorker(15942): Response with redirection code
D/DownloadWorker(15942): Location = [Index path]
D/DownloadWorker(15942): New url: [Index page URL]
D/DownloadWorker(15942): Open connection to [Index page URL]
D/DownloadWorker(15942): Headers = {"authorization": "Basic [Auth-token]","connection": "keep-alive"}
D/DownloadWorker(15942): Content-Type = text/html; charset=utf-8
D/DownloadWorker(15942): Content-Length = -1
D/DownloadWorker(15942): Charset = UTF-8
D/DownloadWorker(15942): Content-Disposition = null
D/DownloadWorker(15942): fileName = Index
D/DownloadWorker(15942): Update notification: {notificationId: 22, title: Index, status: 2, progress: -409600}
D/DownloadWorker(15942): There's no application that can open the file /storage/emulated/0/Download/Index (16)
D/DownloadWorker(15942): Update too frequently!!!!, but it is the final update, we should sleep a second to ensure the update call can be processed
D/DownloadWorker(15942): Update notification: {notificationId: 22, title: Index, status: 3, progress: 100}
D/DownloadWorker(15942): File downloaded
I/WM-WorkerWrapper(15942): Worker result SUCCESS for Work [ id=8e03335b-c319-445e-8622-d22bacf34568, tags={ flutter_download_task, vn.hunghd.flutterdownloader.DownloadWorker } ]
我尝试保存 cookies 并使用 http package 下载文件,但它仍然被重定向。 我需要允许用户从当前的 webview 下载 PDF 文件。
任何解决该问题的建议将不胜感激。
谢谢你。
经过几次尝试,我终于找到了解决方案。 DownloadWorker 被重定向到登录页面,因为尽管用户在 InAppWebView 中经过身份验证,但 flutter 下载器似乎在单独的上下文中运行,因此用户未经过身份验证。
为了维护用户 session,我创建了一个变量:
// Store cookies to save user session for download
String cookiesString = '';
然后,我创建了updateCookies
function 从 CookieManager 检索CookieManager
并更新cookiesString
变量:
Future<void> updateCookies(Uri url) async {
List<Cookie> cookies = await CookieManager().getCookies(url: url);
cookiesString = '';
for (Cookie cookie in cookies) {
cookiesString += '${cookie.name}=${cookie.value};';
}
print(cookiesString);
}
然后,我在 InAppWebView 的onLoadStop
事件监听器中调用updateCookies
:
onLoadStop: (controller, url) async {
pullToRefreshController.endRefreshing();
if (url != null) {
await updateCookies(url);
}
setState(() {
this.url = url.toString();
urlController.text = this.url;
});
},
最后,我将 cookies 传递给onDownloadStart
事件监听器中 FlutterDownloader 的 headers:
await FlutterDownloader.enqueue(
headers: {
HttpHeaders.authorizationHeader: 'Basic ' +
authToken,
HttpHeaders.connectionHeader: 'keep-alive',
HttpHeaders.cookieHeader: cookiesString,
},
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.