LinMinquan's Blog

Experience technology to change life

Flutter Dio https certificate verificate

环境:Flutter 1.17.4, Dio 3.0.9

需要去接入某服务商的API,给的接口是 ip 地址,而不是域名,对方给了个文件(root certificate file) trusted-ca-certs.pem 用来验证 https 连接。看来他们是用的自签名的证书。

根据 参考链接1 去尝试会报错,OS Error: No such file or directory, errno = 2

原因是我忘记把 trusted-ca-certs.pem 写在 pubspec.yaml 里。

最终的代码如下:

Dio dio = new Dio();
ByteData bytes = await rootBundle.load('assets/trusted-ca-certs.pem');
(dio.httpClientAdapter as DefaultHttpClientAdapter).onHttpClientCreate  = (client) {
    SecurityContext sc = new SecurityContext();
    sc.setTrustedCertificatesBytes(bytes.buffer.asUint8List());
    HttpClient httpClient = new HttpClient(context: sc);
    return httpClient;
};

参考链接:

  1. Dio https certificate verification

  2. Add Certificate in Flutter

  3. root certificate


Share