如何在Dart中将数据发布到https服务器? [英] How to post data to https server in dart?

查看:154
本文介绍了如何在Dart中将数据发布到https服务器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我当时正在开发一个应用程序,所以遇到了一个问题。
我需要将JSON数据发布到https服务器。由于该应用程序目前正在开发中,因此我们正在使用自签名证书。

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?

下面是我用来通过 http 向Web服务器发出单个发布请求的代码,但是每当我替换 http https (自签名)时出现错误:


HandshakeException:客户端中的握手错误(操作系统错误:
CERTIFICATE_VERIFY_FAILED:自签名证书(handshake.cc:355))

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":"yyyy@xx.com","name":"xyz"};

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

我对Flutter和Dart很陌生,请帮帮我。

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

推荐答案

http.post 是方便的包装在幕后创建了一个IOClient。您可以将自己的io HttpClient传递给它,这具有禁用证书检查的方法,因此您只需要像这样自己构造它们即可...

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

bool trustSelfSigned 控制是否获得默认行为或允许不良证书。

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

这篇关于如何在Dart中将数据发布到https服务器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆