How to send a custom header in a POST request in Android using webview_flutter

This documentation states that it cannot be done, so I’m looking for an alternative solution:

Currently, setting custom headers when making a post request with the WebViewController’s loadRequest method is not supported on Android. If you require this functionality, a workaround is to make the request manually, and then load the response data using loadHtmlString instead.

The workaround they provide comes with its own issues. The loadHtmlString method only displays an unstyled, unresponsive page in the webview element with the following console errors:

I/chromium(19539): [INFO:CONSOLE(286)] "Uncaught ReferenceError: $ is not defined", source: about:blank (286)
I/chromium(19539): [INFO:CONSOLE(636)] "Uncaught ReferenceError: jQuery is not defined", source: about:blank (636)

Here is my implementation of the loadHtmlString version. I’ve tried loading jQuery to solve the unresponsive issue, but I have no messages related to the ignored stylesheets:

class _PortalWebviewState extends State<PortalWebview> {
  late final WebViewController controller;

  @override
  void initState() {
    super.initState();
    controller = WebViewController()
      ..setJavaScriptMode(JavaScriptMode.unrestricted);
    _loadRequestWithAuthHeader();
    controller.addJavaScriptChannel(
      'Flutter',
      onMessageReceived: (JavaScriptMessage message) {
        print('JavaScript Error: ${message.message}');
     },
   );
  }

  Future<void> injectJQuery() async {
  await controller.runJavaScript('''
    var script = document.createElement('script');
    script.src = 'https://code.jquery.com/jquery-3.6.0.min.js';
    script.type = 'text/javascript';
    document.getElementsByTagName('head')[0].appendChild(script);
    ''');
  }

  Future<void> _loadRequestWithAuthHeader() async {
    const storage = FlutterSecureStorage();
    final token = await storage.read(key: 'token');
    if (token != null) {
      print("Token found in keychain.");
      final url = Uri.parse('${Config.domain}/mobile_index.php');
      final headers = {
        'Authorization': 'Bearer $token',
        'Content-Type': 'application/json',
      };

      try {
        final response = await http.post(url, headers: headers);
        print('Portal response status code: ${response.statusCode}');

        if (response.statusCode == 200) {
          await injectJQuery();
          await controller.loadHtmlString(response.body);
        } else {
          print('Error: ${response.statusCode}');
          // Handle error cases here
        }
      } catch (e) {
        print('Error: $e');
        // Handle exceptions here
      }
    } else {
      print('Token not found');
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      resizeToAvoidBottomInset: true,
      appBar: AppBar(
        title: const Text('COMPANY NAME'),
        actions: [
          NavigationControls(controller: controller),
          // Menu(controller: controller),
        ],
      ),
      body: PortalWebviewStack(controller: controller),
    );
  }

It returns unstyled HTML with broken links that load blank pages – my server logs don’t show that any requests are received after clicking links in the webview.

I believe that sending the auth header as part of a GET request might be an easier solution, but I like the security of POST and believe that this workaround should be possible in my use case since it’s referenced in the docs above and in this Github issue.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật