How to Solve flutter CERTIFICATE_VERIFY_FAILED error while performing a POST request

How to Solve flutter CERTIFICATE_VERIFY_FAILED error while performing a POST request?

When a user runs an application in a mobile application sometimes it randomly starts giving an error that says CERTIFICATE_VERIFY_FAILED. So in this article, we will walk through the same.

How to Solve flutter CERTIFICATE_VERIFY_FAILED error while performing a POST request?

The correct(but a bad) way to do it, as I found out, is to allow all certificates.

HttpClient client = new HttpClient();
client.badCertificateCallback = ((X509Certificate cert, String host, int port) => true);

String url ='[email protected]';

Map map = { 
     "email" : "email" , 
     "password" : "password"
};

HttpClientRequest request = await client.postUrl(Uri.parse(url));

request.headers.set('content-type', 'application/json');

request.add(utf8.encode(json.encode(map)));

HttpClientResponse response = await request.close();

String reply = await response.transform(utf8.decoder).join();

print(reply);

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

  • 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;
      }
    }
  • In your main function, add the following line after function definition:
    HttpOverrides.global = new MyHttpOverrides();

    If you are using Dio library, just do this:

    Dio dio = new Dio();
    (dio.httpClientAdapter as DefaultHttpClientAdapter).onHttpClientCreate =
        (HttpClient client) {
      client.badCertificateCallback =
          (X509Certificate cert, String host, int port) => true;
      return client;
    };

    You can also try with the below code.

    import 'package:http/io_client.dart';
    import 'dart:io';
    import 'package:http/http.dart';
    import 'dart:async';
    import 'dart:convert';
    
        Future getAccessToken(String url) async {
          try {
            final ioc = new HttpClient();
            ioc.badCertificateCallback =
                (X509Certificate cert, String host, int port) => true;
            final http = new IOClient(ioc);
            http.post('url', body: {"email": "[email protected]", "password": "1234"}).then(
                (response) {
              print("Reponse status : ${response.statusCode}");
              print("Response body : ${response.body}");
              var myresponse = jsonDecode(response.body);
              String token = myresponse["token"];
            });
          } catch (e) {
            print(e.toString());
          }
        }

    The best approach is to allow certificate for trusted hosts, so if your API host is “api.my_app” you can allow certificates from this host only:

    HttpClient client = new HttpClient();
    client.badCertificateCallback = ((X509Certificate cert, String host, int port) {
     final isValidHost = host == "api.my_app";
     return isValidHost;
    });

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);

Use tls 1.3 request URL, no problem. Example

import 'dart:io';

main() async {
  HttpClient client = new HttpClient();
  // tls 1.2 error
//  var request = await client.getUrl(Uri.parse('https://shop.io.mi-img.com/app/shop/img?id=shop_88f929c5731967cbc8339cfae1f5f0ec.jpeg')); 
  // tls 1.3 normal
  var request = await client.getUrl(Uri.parse('https://ae01.alicdn.com/kf/Ud7cd28ffdf6e475c8dc382380d5d1976o.jpg'));
  var response = await request.close();
  print(response.headers);
  client.close(force: true);
}

Conclusion:

Thanks for Reading !!! Stay connected with us on this Flutter Journey:)

So in this article, we have been through how to Solve flutter CERTIFICATE_VERIFY_FAILED error while performing a POST request in Flutter.

Don’t forget to drop your valuable Suggestions/feedback in the comments right below!!!

Keep Learning !!! Keep Fluttering !!!

Still, need Support for Flutter Development? Do let us know, we would love to assist you.

Flutter Agency is our portal Platform dedicated to Flutter Technology and Flutter Developers. The portal is full of cool resources from Flutter like Flutter Widget GuideFlutter ProjectsCode libs and etc.

Flutter Agency is one of the most popular online portals dedicated to Flutter Technology and daily thousands of unique visitors come to this portal to enhance their knowledge of Flutter.

Nirali Patel

Written by Nirali Patel

Nirali Patel is a dedicated Flutter developer with over two years of experience, specializing in creating seamless mobile applications using Dart. With a passion for crafting user-centric solutions, Nirali combines technical proficiency with innovative thinking to push the boundaries of mobile app development.

Leave a comment

Your email address will not be published. Required fields are marked *


ready to get started?

Fill out the form below and we will be in touch soon!

"*" indicates required fields

✓ Valid number ✕ Invalid number
our share of the limelight

as seen on