Flutter webview 拦截并为所有请求添加标头 [英] Flutter webview intercept and add headers to all requests

查看:108
本文介绍了Flutter webview 拦截并为所有请求添加标头的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 webview_flutter 包,我可以加载我的网站并将会话 cookie 添加到初始 URL.

Using the webview_flutter package i could load my website and add session cookies to the initial URL.

_controller.future.then((controller) {
  _webViewController = controller;
  Map<String, String> header = {'Cookie': 'ci_session=${widget.sessionId}'};
  _webViewController.loadUrl('https://xxxx.com', headers: header);
});

为了保持会话的进行,我需要为所有请求添加相同的标头,而不仅仅是初始请求.有没有办法拦截所有请求并通过向它们添加标头来修改它们?

In order to keep the session going i need to add the same header for all requests not just for the initial one. Is there any way to intercept all requests and modify them by adding headers to them?

我发现的最接近的是 navigationDelegate 但它只返回一个 NavigationDecision 这对我来说没有用.

the closest thing i found was navigationDelegate but it only returns a NavigationDecision which isn't useful in my case.

推荐答案

你可以使用我的插件 flutter_inappwebview,这是一个 Flutter 插件,允许你添加内联 WebViews 或打开应用内浏览器窗口,并且有很多事件、方法和选项来控制 WebViews.

You can use my plugin flutter_inappwebview, which is a Flutter plugin that allows you to add inline WebViews or open an in-app browser window and has a lot of events, methods, and options to control WebViews.

如果您需要为每个请求添加自定义标头,您可以使用 shouldOverrideUrlLoading 事件(您需要使用 useShouldOverrideUrlLoading: true 选项启用它).

If you need to add custom headers for each request, you can use the shouldOverrideUrlLoading event (you need to enable it using useShouldOverrideUrlLoading: true option).

相反,如果您需要向 WebView 添加 cookie,您只需使用 CookieManager 类(CookieManager.setCookie 方法来设置 cookie).

Instead, if you need to add cookies to your WebView, you can just use the CookieManager class (CookieManager.setCookie method to set a cookie).

以下是在 WebView 中设置 cookie(名为 ci_session)并为每个请求设置自定义标头(名为 My-Custom-Header)的示例:

Here is an example that set a cookie (named ci_session) in your WebView and also set a custom header (named My-Custom-Header) for each request:

import 'dart:async';
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter_inappwebview/flutter_inappwebview.dart';

Future main() async {
  WidgetsFlutterBinding.ensureInitialized();
  runApp(MyApp());
}

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => new _MyAppState();
}

class _MyAppState extends State<MyApp> {
  InAppWebViewController webView;
  CookieManager _cookieManager = CookieManager.instance();

  @override
  void initState() {
    super.initState();

    _cookieManager.setCookie(
      url: "https://github.com/",
      name: "ci_session",
      value: "54th5hfdcfg34",
      domain: ".github.com",
      isSecure: true,
    );
  }

  @override
  void dispose() {
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('InAppWebView Example'),
        ),
        body: Container(
            child: Column(children: <Widget>[
          Expanded(
              child: InAppWebView(
            initialUrl: "https://github.com/",
            initialHeaders: {'My-Custom-Header': 'custom_value=564hgf34'},
            initialOptions: InAppWebViewGroupOptions(
              crossPlatform: InAppWebViewOptions(
                debuggingEnabled: true,
                useShouldOverrideUrlLoading: true
              ),
            ),
            onWebViewCreated: (InAppWebViewController controller) {
              webView = controller;
            },
            onLoadStart: (InAppWebViewController controller, String url) {},
            onLoadStop: (InAppWebViewController controller, String url) async {
              List<Cookie> cookies = await _cookieManager.getCookies(url: url);
              cookies.forEach((cookie) {
                print(cookie.name + " " + cookie.value);
              });
            },
            shouldOverrideUrlLoading: (controller, shouldOverrideUrlLoadingRequest) async {
              print("URL: ${shouldOverrideUrlLoadingRequest.url}");

              if (Platform.isAndroid || shouldOverrideUrlLoadingRequest.iosWKNavigationType == IOSWKNavigationType.LINK_ACTIVATED) {
                controller.loadUrl(url: shouldOverrideUrlLoadingRequest.url, headers: {
                  'My-Custom-Header': 'custom_value=564hgf34'
                });
                return ShouldOverrideUrlLoadingAction.CANCEL;
              }
              return ShouldOverrideUrlLoadingAction.ALLOW;
            },
          ))
        ])),
      ),
    );
  }
}

这篇关于Flutter webview 拦截并为所有请求添加标头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆