Flutter 使用 http.dart 添加客户端证书以请求

Flutter add client certificate to request using http.dart

我正在尝试从 http.dart 包中将客户端证书加载到 http.client。

关于如何使用 HttpClient class,我看到了多个答案, 喜欢这个答案:,基本上建议执行以下代码

ByteData data = await rootBundle.load('assets/raw/certificate.pfx');
SecurityContext context = SecurityContext.defaultContext;
context.useCertificateChainBytes(data.buffer.asUint8List());
context.usePrivateKeyBytes(data.buffer.asUint8List());
client = HttpClient(context: context);

但我必须使用 http.dart 包,因为我有一个接受 http.client 的函数 像这样

import 'package:http/http.dart' as http;

var httpClient = http.Client();
// i'd like to configure this httpClient to use a specific client certificate

var client = MyClient(httpClient);

....

MyClient (http.Client? httpClient) {
    -- some constructor logic --
}

有什么方法可以配置 http.client 使用客户端证书吗?

谢谢。

不要使用 http.Client() 构造函数。相反,构造一个 IOClient(它是 Client 的子类,可以代替使用)。传递你的 HttpClient.

import 'dart:io';

import 'package:http/io_client.dart';

void main() async {
  final context = SecurityContext.defaultContext;
  // modify context as needed
  final httpClient = HttpClient(context: context);
  final client = IOClient(httpClient);

  await client.get(Uri.parse('https://somewhere.io'));
}