发起 HTTP 网络请求

发起 HTTP 网络请求

对于大多数应用程序来说都需要从互联网上获取数据。在 Flutter 中,http 包提供了从互联网获取数据的最简单的途径。

如何通过 API 调用来获得数据呢?

React Native 提供 Fetch API 实现网络编程,你可以发起请求,然后接收响应来获得数据。

// React Native
_getIPAddress = () => {
  fetch('https://httpbin.org/ip')
    .then(response => response.json())
    .then(responseJson => {
      this.setState({ _ipAddress: responseJson.origin });
    })
    .catch(error => {
      console.error(error);
    });
};

Flutter 使用 http 包。如果要安装 http 包,将它添加到 pubspec.yaml 的 dependencies 部分。

dependencies:
  flutter:
    sdk: flutter
  http: <latest_version>

Flutter 使用 dart:io 提供核心的 HTTP 客户端支持,要创建一个 HTTP 客户端,引用 dart:io。

import 'dart:io';

客户端支持如下所列的 HTTP 操作:GET, POST, PUT 和 DELETE。

// Flutter
final url = Uri.https('httpbin.org', 'ip');
final httpClient = HttpClient();
_getIPAddress() async {
  var request = await httpClient.getUrl(url);
  var response = await request.close();
  var responseBody = await response.transform(utf8.decoder).join();
  String ip = jsonDecode(responseBody)['origin'];
  setState(() {
    _ipAddress = ip;
  });
}

API calls on Android Android

API calls on iOS iOS