how to solve flutter CERTIFICATE_VERIFY_FAILED error while performing a POST request?

前端 未结 8 1328
孤街浪徒
孤街浪徒 2020-11-27 19:54

I am sending a post request in Dart. It is giving a response when I test it on API testing tools such as Postman. But when I run the app. It gives me the following error:- <

相关标签:
8条回答
  • 2020-11-27 20:56

    Just for the sake of clarity specially for the new comers to flutter/dart, here is what you need to do in order to enable this option globally in your project:

    1. In your main.dart file, add or import the following class:
     class MyHttpOverrides extends HttpOverrides{
      @override
      HttpClient createHttpClient(SecurityContext context){
        return super.createHttpClient(context)
          ..badCertificateCallback = (X509Certificate cert, String host, int port)=> true;
      }
    }
    
    1. In your main function, add the following line after function definition:

    HttpOverrides.global = new MyHttpOverrides();

    This comment was very helpful to pass through this matter

    0 讨论(0)
  • 2020-11-27 20:56

    I specifically needed to use lib/client.dart Client interface for http calls (i.e. http.Client instead of HttpClient) . This was required by ChopperClient (link).

    So I could not pass HttpClient from lib/_http/http.dart directly to Chopper. ChopperClient can receive HttpClient in the constructor wrapped in ioclient.IOClient.

    HttpClient webHttpClient = new HttpClient();
    webHttpClient.badCertificateCallback = ((X509Certificate cert, String host, int port) => true);
    dynamic ioClient = new ioclient.IOClient(webHttpClient);
    final chopper = ChopperClient(
      baseUrl: "https://example.com",
      client: ioClient,
      services: [
        MfService.create()
      ],
      converter: JsonConverter(),
    );
    final mfService = MfService.create(chopper);
    

    This way you can temporarily ignore CERTIFICATE_VERIFY_FAILED error in your calls. Remember - that's only for development purposes. Don't use this in production environment!

    0 讨论(0)
提交回复
热议问题