Flutter Java

CERTIFICATE_VERIFY_FAILED Error while performing a POST Request In Flutter

When Sending a post request in Dart. It is giving a response when We test it on API testing tools such as Postman. But when We run the app. It gives the following error:-

E/flutter ( 6264): HandshakeException: Handshake error in client (OS Error: E/flutter ( 6264):  CERTIFICATE_VERIFY_FAILED: unable to get local issuer certificate(handshake.cc:363))

Here is what you need to do in order to enable this option globally in your project:

Method :- 1

Step 1:

In your main.dart file, add or import the following class:

 class PostHttpOverrides extends HttpOverrides{
  @override
  HttpClient createHttpClient(SecurityContext context){
    return super.createHttpClient(context)
      ..badCertificateCallback = (X509Certificate cert, String host, int port)=> true;
  }
}

Step 2:

Add the following line after function definition In your main function:

HttpOverrides.global = new PostHttpOverrides();

Method :- 2

If you are using Dio library, just do this in your post method :

 final ioc = new HttpClient();
   ioc.badCertificateCallback = (X509Certificate cert, String host, int port) => true;
   final http = new IOClient(ioc);

Full Code

import 'package:http/io_client.dart';
import 'dart:io';
import 'package:http/http.dart';
import 'dart:async';
import 'dart:convert';

    Future HttpPostMethod() 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": "abc@xyz.com", "password": "12345"}).then(
            (response) {
          print("Reponse status : ${response.statusCode}");
          print("Response body : ${response.body}");
          var myresponse = jsonDecode(response.body);
          print(myresponse)
        });
      } catch (e) {
        print(e.toString());
      }
    }

Leave a Reply

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