如何为Flutter http创建本地SSL证书用于开发测试
本地Flutter HTTP测试的两种解决方案
一、无需SSL证书的最优方案(推荐)
直接在HTTP客户端中禁用SSL证书验证,完全适配本地开发测试场景:
- 利用Flutter自带的
dart:io模块,创建自定义HttpClient并跳过证书校验:
import 'dart:io'; import 'package:http/http.dart' as http; Future<http.Response> fetchLocalData() async { final httpClient = HttpClient() ..badCertificateCallback = ((X509Certificate cert, String host, int port) => true); final client = http.IOClient(httpClient); try { return await client.get(Uri.parse('https://localhost:3000/api/data')); } finally { client.close(); } }
- 注意:仅用于本地测试,上线前必须删除此逻辑,否则会引入严重安全风险。
二、手动生成本地SSL证书详细步骤
如果业务要求必须使用SSL证书,可通过OpenSSL生成完整的证书文件(包含cert和pem格式私钥):
步骤1:生成RSA私钥(.pem)
打开终端执行命令:
openssl genrsa -out localhost.key 2048
执行后会得到localhost.key文件,这就是pem格式的私钥。
步骤2:生成证书签名请求(CSR)
执行命令,按提示填写信息(本地测试可直接回车跳过大部分字段,Common Name必须填localhost或你的本地IP,比如192.168.1.100):
openssl req -new -key localhost.key -out localhost.csr
步骤3:生成自签名证书(.cert/.crt)
用私钥和CSR生成有效期365天的自签名证书:
openssl x509 -req -days 365 -in localhost.csr -signkey localhost.key -out localhost.crt
此时你会得到localhost.crt(即cert格式证书文件)和之前的localhost.key。
步骤4:服务器配置与Flutter端信任
- 将
localhost.key和localhost.crt配置到你的REST服务器中(比如Node.js Express、Python FastAPI等),启用HTTPS服务。 - 将
localhost.crt复制到Flutter项目的assets/certs目录,在pubspec.yaml中声明资源:
assets: - assets/certs/localhost.crt
- 在Flutter客户端加载并信任该证书:
import 'dart:io'; import 'dart:typed_data'; import 'package:flutter/services.dart'; import 'package:http/http.dart' as http; Future<http.Response> fetchSecureLocalData() async { final ByteData certData = await rootBundle.load('assets/certs/localhost.crt'); final List<int> certBytes = certData.buffer.asUint8List(); final SecurityContext context = SecurityContext() ..setTrustedCertificatesBytes(certBytes); final httpClient = HttpClient(context: context); final client = http.IOClient(httpClient); try { return await client.get(Uri.parse('https://localhost:3000/api/data')); } finally { client.close(); } }
三、关于IP地址的说明
- 证书的Common Name(CN)必须与你访问的地址完全一致:用
localhost访问就填localhost,用本地IP访问就填对应IP。 - 若需要同时支持
localhost和多个本地IP,可生成多域名/IP证书:- 创建
openssl.cnf配置文件:
- 创建
[req] distinguished_name = req_distinguished_name x509_extensions = v3_req prompt = no [req_distinguished_name] CN = localhost [v3_req] subjectAltName = @alt_names [alt_names] DNS.1 = localhost IP.1 = 192.168.1.100 IP.2 = 127.0.0.1
- 重新生成CSR:
openssl req -new -key localhost.key -out localhost.csr -config openssl.cnf
- 再执行证书生成命令,最终证书即可支持配置中的所有域名和IP。
内容的提问来源于stack exchange,提问作者Paul Coshott
相关产品推荐
相关产品推荐

