我只是想绕过证书验证,但我收到错误,未为客户端定义 badCertificateCallback 。你知道我怎样才能做到这一点吗?
谢谢你。
这是我的实际代码
http.Client client = http.Client();
HttpClient() {
// Load the PEM certificate file during class initialization
loadCertificate();
}
Future<void> loadCertificate() async {
// Load the certificate asset
ByteData data = await rootBundle.load('assets/certificate.pem');
// Convert the ByteData to a List<int>
List<int> bytes = data.buffer.asUint8List();
// Configure the default HTTP client to use the certificate
SecurityContext securityContext = SecurityContext.defaultContext;
securityContext.setTrustedCertificatesBytes(bytes);
// Set the badCertificateCallback
client.badCertificateCallback = (X509Certificate cert, String host, int port) {
// Always trust the certificate
return true;
};`
尝试使用 .. 级联运算符:
void main() async {
HttpClient client = new HttpClient()
..badCertificateCallback =
((X509Certificate cert, String host, int port) => true);
HttpClientRequest request = await client.getUrl(Uri.parse('https://your-url.com'));
HttpClientResponse response = await request.close();
// Handle your response...
}
这就是我用于configure_nonweb.dart的
///allows calls to override a bad https certificate
///
///only used in non-web code
void overRideHttps() {
HttpOverrides.global = MyHttpOverrides();
}
///ignore bad certificates
class MyHttpOverrides extends HttpOverrides {
@override
HttpClient createHttpClient(SecurityContext? context) =>
super.createHttpClient(context)
..badCertificateCallback =
(X509Certificate cert, String host, int port) => true;
}
在我的 main() 函数中,我调用: 覆盖RideHttps();
要导入文件,我会查看是否正在使用网络:
import 'unsupported.dart'
if (dart.library.io) 'configure_nonweb.dart'
if (dart.library.html) 'configure_web.dart';
在文件 unsupported.dart 中放入:
void overRideHttps() {
throw UnsupportedError('');
}