api - 如何在 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);
});
我检查了下面的几个链接以及更多链接,并尝试了所有链接,但似乎没有任何效果。
- 如何解决 SocketException: Failed host lookup: 'www.xyz.com' (OS Error: No address associated with hostname, errno = 7)
- https://github.com/flutter/flutter/issues/27883
另请注意,我可以从浏览器访问服务器。同样的服务器也可以从 iOS 应用程序访问(使用 XCode 构建)。从 iOS 我可以访问服务器。
请帮忙!!!
解决方案
该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插件
推荐阅读
- microcontroller - 使用 UART 同步两个微控制器之间的串行通信的最佳方法是什么?
- php - 如何在codeigniter中限制同一用户多次登录另一个系统
- google-cloud-platform - 将子域重定向到谷歌云
- php - Laravel 6 - Illuminate\Database\Eloquent\RelationNotFoundException 调用未定义的关系
- php - “错误:插入”非特定插入错误
- ios - 如何在 Xcode UI 测试中获得授权部分
- php - GROUP_BY 中的错误,查询来自两个数据库 CODEIGNITER
- regex - 参数扩展正则表达式?
- c - 在使用递归函数调用时何时使用'return'?
- android - 如何将来自 API 的一些 JSON 数据存储在房间数据库中?