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(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();
Full Code
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:point/routes.dart';
import 'package:point/theme.dart';
import 'login/LoginScreen.dart';
class PostHttpOverrides extends HttpOverrides{
@override
HttpClient createHttpClient( context){
return super.createHttpClient(context)
..badCertificateCallback = (X509Certificate cert, String host, int port)=> true;
}
}
void main() {
HttpOverrides.global = new PostHttpOverrides();
runApp(MyApp());
}
class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Flutter Demo',
theme: theme(),
// home: SplashScreen(),
// We use routeName so that we dont need to remember the name
initialRoute: LoginScreen.routeName,
routes: routes,
);
}
}
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());
}