简体   繁体   English

flutter_inappwebview 和 flutter_downloader - 不知道我做错了什么?

[英]flutter_inappwebview and flutter_downloader - not sure what I'm doing wrong?

Upfront info:前期资料:

Language: Flutter/Dart
Flutter Packages: flutter_inappwebview, flutter_downloader

I'm having an issue with a mobile application I'm building for Android using Flutter.我正在使用 Flutter 为 Android 构建移动应用程序时遇到问题。 One function of the app is to be able to download links that are associated with PDF files.该应用程序的一个 function 是能够下载与 PDF 文件关联的链接。 These files are located on the server that the app is already accessing.这些文件位于应用程序已经访问的服务器上。 A user has already logged in through the app so authentication has been established.用户已通过应用程序登录,因此已建立身份验证。 When a URL is clicked that has a PDF it performs a redirect and the homepage (an index.php) is returned and downloaded instead.当单击具有 PDF 的 URL 时,它会执行重定向并返回并下载主页(index.php)。 I am at a loss as to how this is happening but I have thoughts.我不知道这是如何发生的,但我有想法。

  1. I need to have the download occur in the current webview (as in same session and window).我需要在当前的 webview 中进行下载(如在相同的 session 和窗口中)。
  2. Disable URL redirection.禁用 URL 重定向。
  3. Figure out why the link is being redirected for authentication (assumption as it's redirecting to the homepage).弄清楚为什么要重定向链接以进行身份验证(假设它正在重定向到主页)。

Any thoughts or help would be appreciated.任何想法或帮助将不胜感激。 Happy to provide more information as well.也很高兴提供更多信息。

In main.dart:在 main.dart 中:

onDownloadStart: (controller, url) async {
                print("onDownloadStart $url");
                final taskId = await FlutterDownloader.enqueue(
                  headers: {'My-Custom-Header': 'custom_value=564hgf34'},
                  url: url,
                  savedDir: (await getExternalStorageDirectory()).path,
                  showNotification: true, // show download progress in status bar (for Android)
                  openFileFromNotification: true, // click on notification to open downloaded file (for Android)
                );
                return taskId;
              },

Logging:记录:

I/flutter (28552): onDownloadStart https://hjhvtc.online/pluginfile.php/6723/mod_resource/content/1/Automotive%20industry%20jobs.pdf
W/WM-WorkSpec(28552): Backoff delay duration less than minimum value
D/DownloadWorker(28552): DownloadWorker{url=https://hjhvtc.online/pluginfile.php/6723/mod_resource/content/1/Automotive%20industry%20jobs.pdf,filename=null,savedDir=/storage/emulated/0/Android/data/com.coffeepaulconsulting.hjhvtconline/files,header={"My-Custom-Header": "custom_value=564hgf34"},isResume=false
D/DownloadWorker(28552): Update notification: {notificationId: 1, title: https://hjhvtc.online/pluginfile.php/6723/mod_resource/content/1/Automotive%20industry%20jobs.pdf, status: 2, progress: 0}
D/DownloadWorker(28552): Open connection to https://hjhvtc.online/pluginfile.php/6723/mod_resource/content/1/Automotive%20industry%20jobs.pdf
D/DownloadWorker(28552): Headers = {"My-Custom-Header": "custom_value=564hgf34"}
D/DownloadWorker(28552): Response with redirection code
D/DownloadWorker(28552): Location = https://hjhvtc.online/login/index.php
D/DownloadWorker(28552): New url: https://hjhvtc.online/login/index.php
D/DownloadWorker(28552): Open connection to https://hjhvtc.online/login/index.php
D/DownloadWorker(28552): Headers = {"My-Custom-Header": "custom_value=564hgf34"}
V/InputMethodManager(28552): b/117267690: Failed to get fallback IMM with expected displayId=197 actual IMM#displayId=0 view=com.pichillilorenzo.flutter_inappwebview.InAppWebView.InAppWebView{4592e22 VFEDHVCL. ......ID 0,0-1080,1997}
D/DownloadWorker(28552): Content-Type = text/html; charset=utf-8
D/DownloadWorker(28552): Content-Length = -1
D/DownloadWorker(28552): Charset = UTF-8
D/DownloadWorker(28552): Content-Disposition = null
D/DownloadWorker(28552): fileName = index.php
D/DownloadWorker(28552): Update too frequently!!!!, this should be dropped
D/DownloadWorker(28552): There's no application that can open the file /storage/emulated/0/Android/data/com.coffeepaulconsulting.hjhvtconline/files/index.php
D/DownloadWorker(28552): Update too frequently!!!!, but it is the final update, we should sleep a second to ensure the update call can be processed
D/DownloadWorker(28552): Update notification: {notificationId: 1, title: index.php, status: 3, progress: 100}
D/DownloadWorker(28552): File downloaded
I/WM-WorkerWrapper(28552): Worker result SUCCESS for Work [ id=633dd93d-99e3-46e2-937d-a4782d62a569, tags={ flutter_download_task, vn.hunghd.flutterdownloader.DownloadWorker } ]

I've finally found the solution after several tries.经过几次尝试,我终于找到了解决方案。 The DownloadWorker is redirected to the login page because although the user is authenticated in the InAppWebView, the flutter downloader seems to run in a separate context so the user is not authenticated. DownloadWorker 被重定向到登录页面,因为尽管用户在 InAppWebView 中经过身份验证,但 flutter 下载器似乎在单独的上下文中运行,因此用户未经过身份验证。

To maintain the user session, I created a variable:为了维护用户 session,我创建了一个变量:

  // Store cookies to save user session for download
  String cookiesString = '';

Then, I created the updateCookies function that retrieves the cookies from the CookieManager and update the cookiesString variable:然后,我创建了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);
  }

Then, I call updateCookies in the onLoadStop event listener of InAppWebView:然后,我在 InAppWebView 的onLoadStop事件监听器中调用updateCookies

onLoadStop: (controller, url) async {
    pullToRefreshController.endRefreshing();

    if (url != null) {
        await updateCookies(url);
    }

    setState(() {
        this.url = url.toString();
        urlController.text = this.url;
    });
},

Finally, I pass the cookies to the headers of FlutterDownloader in the onDownloadStart event listener:最后,我将 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.

相关问题 将flutter_downloader与flutter_inappwebview一起使用-带有重定向代码的响应 - Using flutter_downloader with flutter_inappwebview - Response with redirection code flutter_downloader 在发布版本中,它会崩溃(在 Android 上) - flutter_downloader In the release version, it crashes (on Android) 无法使用 flutter_downloader 下载 - Can't download using flutter_downloader flutter_downloader 插件不适用于现有项目 - flutter_downloader plugin is not working on existing project flutter 错误:任务“:flutter_inappwebview:compileDebugJavaWithJavac”执行失败 - flutter error: Execution failed for task ':flutter_inappwebview:compileDebugJavaWithJavac' 为什么我使用 flutter_downloader 下载有时会失败? - Why do my downloads fail sometimes using flutter_downloader? 无法在 Flutter_downloader 的 Android 中打开下载的文件 - Unable to open downloaded file in Android for flutter_downloader java.lang.IllegalStateException:尝试创建未注册类型的平台视图:com.pichillilorenzo/flutter_inappwebview - java.lang.IllegalStateException: Trying to create a platform view of unregistered type: com.pichillilorenzo/flutter_inappwebview android进程崩溃与简单的应用程序在adb上,不确定我在做什么错 - android process crash on adb with simple app, not sure what i'm doing wrong 我用SurfaceView做错了什么? - What I'm doing wrong with SurfaceView?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM