【问题标题】:How to make an HTTP POST from Flutter to a local cloud functions server如何从 Flutter 向本地云功能服务器发送 HTTP POST
【发布时间】:2020-05-24 03:14:05
【问题描述】:

如何从 Android 上的 Flutter 应用程序向本地运行的 Firebase 云功能服务器发出 POST 请求?

这是我的代码:

{
  print("good email");
  String url = 'http://10.0.2.2:5000/mattsapp/api1'; //I have also tried replacing this with localhost
  String json = '{"email": "a@gmail.com", "username": "user1", "password":"111111"}';

  Future<void> loginPost() async {
    http.Response resp = await http.post(url, body: json);
    print(resp);
  }
  loginPost();
}

当我运行代码时,连接超时。当我将10.0.2.2 替换为localhost 时,出现以下错误:

 Unhandled Exception: SocketException: OS Error: Connection refused, errno = 111, address = localhost, port = 58912

当我和邮递员一起跑到http://localhost:5000/mattsapp/api1 时,它工作正常。

【问题讨论】:

  • 尝试在您的请求标头中添加标头:HttpHeaders.contentTypeHeader: "application/x-www-form-urlencoded"
  • 嗨@Federick Jonathan。我怎么做。我只是在发布请求中添加它。例如:await http.post(url, body: json, header: "application/x-www-form-urlencoded"?
  • http.post(url, body: json, headers: {HttpHeaders.contentTypeHeader: "application/x-www-form-urlencoded"},)。我的错,标题应该接收地图
  • 还是不行。它仍在运行,只是会超时。
  • 是的,它只是超时了。

标签: firebase flutter dart google-cloud-functions


【解决方案1】:

根据这个connect_functions和这个clear_text_traffic_permitted

打算仅使用安全连接连接到目标的应用程序可以选择不支持到这些目标的明文(使用未加密的 HTTP 协议而不是 HTTPS)。此选项有助于防止由于后端服务器等外部来源提供的 URL 更改而导致应用程序意外回归。

创建一个xml文件/android/app/src/main/res/xml/network_security_config.xml并将代码放入文件中。

<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
    <domain-config cleartextTrafficPermitted="true">
        <domain includeSubdomains="true">localhost</domain>
        <domain includeSubdomains="true">10.0.2.2</domain>
    </domain-config>
</network-security-config>

导航到主文件夹中的 AndroidManifest.xml:/android/app/src/main/AndroidManifest.xml

在应用程序标签中添加networkSecurityConfig,如下所示:

 <application
        android:networkSecurityConfig="@xml/network_security_config">
        ...
 </application>

注意:这不适用于真实设备,但适用于模拟器。如果要使用真机,需要在network_security_config.xml中将10.0.0.2替换成热点或wifi等其他ip地址。

【讨论】:

    猜你喜欢
    • 2017-09-10
    • 2019-01-23
    • 1970-01-01
    • 1970-01-01
    • 2010-09-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-08
    相关资源
    最近更新 更多