Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.3k views
in Technique[技术] by (71.8m points)

flutter - How to post data to https server in dart?

So i was building an application in flutter and I came across a problem. I need to post JSON data to a https server. Since the application is currently under development so we are using Self-Signed Certificate.

How can I achieve this in dart language?

Below is the code which I use to make single post request to the web server over http, but whenever I replace the http with https(Self Signed) I get an error:

HandshakeException: Handshake error in client (OS Error: CERTIFICATE_VERIFY_FAILED: self signed certificate(handshake.cc:355))

 var url = 'http://192.168.1.40/registration.php'; //or https
 var data = {"email":"[email protected]","name":"xyz"};

 http.post(url, body:data)
     .then((response) {
   print("Response status: ${response.statusCode}");
   print("Response body: ${response.body}");
 }).catchError((error) => print(error.toString()));

I am pretty new to Flutter and Dart please help me out. Suggestions will be welcomed.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

http.post is a convenience wrapper which creates a IOClient under the hood. You can pass your own io HttpClient to this, and that has a way to disable the certificate checks, so you just have to construct them yourself like this...

  bool trustSelfSigned = true;
  HttpClient httpClient = new HttpClient()
    ..badCertificateCallback =
        ((X509Certificate cert, String host, int port) => trustSelfSigned);
  IOClient ioClient = new IOClient(httpClient);
  ioClient.post(url, body:data);

  // don't forget to call ioClient.close() when done
  // note, this also closes the underlying HttpClient

the bool trustSelfSigned controls whether you get the default behaviour or allows bad certificates.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...