3

enter image description here

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:-

Here is my code of the function -

var request =
    http.MultipartRequest('POST', Uri.parse('https://myurl/files/'));
request.files.add(await http.MultipartFile.fromPath('file', pathfile));

http.StreamedResponse response = await request.send();
if (response.statusCode == 200) {
  print(await response.stream.bytesToString());
} else {
  print(response.reasonPhrase);
}

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))
Sutirath
  • 61
  • 1
  • 1
  • 5

1 Answers1

10
 **main.dart**

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

void main() async {
WidgetsFlutterBinding.ensureInitialized();
HttpOverrides.global = new MyHttpOverrides();
runApp(Myapp());}
PeNToR
  • 118
  • 1
  • 3
  • I was struggling with the exact same problem and this somehow solved it. Can you please explain what causes this problem and how it can maybe be fixed permanently? Is this a bug in Flutter? In a plugin? Thanks! – Teun K Nov 26 '21 at 13:50
  • 5
    @TeunK Typically with a REST API you are accessing a website via your browser. The browser has access to the system CA certificate store. The browser takes the web address and gets the certificate from it, then it validates it against the CA certificates stored on the system. Near as I can tell, Flutter has no access to this system CA certificate store. As such, you have to manually tell it what certs to trust. The code above is actually defeating the purpose of TSL certificates by not validating the cert. This answer is good for testing only. – TheFunk Dec 30 '21 at 20:24