首页 > 解决方案 > 如何在 Flutter 中进行 https 调用?

问题描述

我是颤振开发的新手。我正在努力使 https 调用正常工作。每当我调用 https url 时,它都会引发以下错误:

SocketException:主机查找失败:“someserver.com”(操作系统错误:提供节点名或服务名,或未知,errno = 8)

下面是我正在使用的代码,

final ioc = new HttpClient();
    ioc.badCertificateCallback =
        (X509Certificate cert, String host, int port) => true;
    final http = new IOClient(ioc);
    return http
        .post(url, body: body, headers: headers, encoding: encoding)
        .then((response) {
      final String res = response.body;
      final int statusCode = response.statusCode;

      if (statusCode < 200 || statusCode > 400 || json == null) {
        throw new Exception("Error while posting data");
      }
      return _decoder.convert(res);
    });

我检查了下面的几个链接以及更多链接,并尝试了所有链接,但似乎没有任何效果。

另请注意,我可以从浏览器访问服务器。同样的服务器也可以从 iOS 应用程序访问(使用 XCode 构建)。从 iOS 我可以访问服务器。

请帮忙!!!

标签: apiflutterhttpweb-serviceshttps

解决方案


http软件包提供了从 Internet 获取数据的最简单方法。

要安装http包,请将其添加到pubspec.yaml文件的依赖项部分。您可以在此处找到最新版本的http软件包

dependencies:
  http: <latest_version>

导入http包。

import 'package:http/http.dart' as http;

此外,在您的AndroidManifest.xml文件中,添加 Internet 权限。

<uses-permission android:name="android.permission.INTERNET" />

然后像下面的函数一样,您将能够获取/获取/发布 HTTP 调用

Future<http.Response> getchData() {
  return http.get('https://jsonplaceholder.typicode.com/albums/1');
}

对于高级 HTTP 调用和管理,您可以使用Dio插件


推荐阅读