How to solve Flutter CERTIFICATE_VERIFY_FAILED error while performing a POST request?

2 Min Read

The “CERTIFICATE_VERIFY_FAILED” error in Flutter can occur when making a secure HTTPS request if the server’s SSL certificate is not trusted. This can happen if the certificate is self-signed, or if it was issued by a certificate authority that is not included in the list of trusted CAs on your device.

To solve this error, you can either add the certificate to your device’s list of trusted CAs, or you can bypass the certificate validation by setting the validateCertificate property of the HttpClient object to false. However, this is not recommended, as it could leave your app vulnerable to man-in-the-middle attacks.

Here’s an example of how to make a secure HTTPS POST request in Flutter and bypass certificate validation:

import 'dart:io';
import 'dart:convert';

void main() async {
  HttpClient httpClient = new HttpClient();
  httpClient.badCertificateCallback =
      (X509Certificate cert, String host, int port) => true;

  HttpClientRequest request = await httpClient.postUrl(Uri.parse(""));
  request.headers.set('content-type', 'application/json');
  request.add(utf8.encode(json.encode({"key": "value"})));
  HttpClientResponse response = await request.close();

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

In this example, the badCertificateCallback property of the HttpClient object is set to a function that always returns true, which means that it will accept any certificate regardless of its validity.

Again, please note that bypassing certificate validation is not recommended and should only be done in exceptional cases, as it could leave your app vulnerable to security threats. If possible, try to obtain a valid certificate from a trusted CA and add it to your device’s list of trusted CAs.

Share this Article
Leave a comment