skip to Main Content

I just want to bypass the certificate verification but I het the error that the badCertificateCallback is not defined for client. Do you know how can I make this work?

Thank you.

This is my actual code

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;
    };`

2

Answers


  1. Try using the .. cascade operator:

    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...
    }
    
    Login or Signup to reply.
  2. This is what I use for 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;
    }
    

    In my main() function I call:
    overRideHttps();

    To import the file, I look to see if I’m using the web or not:

    import 'unsupported.dart'
        if (dart.library.io) 'configure_nonweb.dart'
        if (dart.library.html) 'configure_web.dart';
    

    in file unsupported.dart put:

    void overRideHttps() {
      throw UnsupportedError('');
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search