Flutter网络请求插件http的使用
Flutter网络请求插件http的使用
简介
package:http
是一个基于 Future 的 HTTP 请求库,提供了简单易用的方法来发起 HTTP 请求。它支持多平台(移动端、桌面端和浏览器),并且可以轻松地与多种实现集成。
使用方法
基本用法
最简单的方式是通过顶层函数发起 HTTP 请求:
import 'package:http/http.dart' as http;
void main() async {
var url = Uri.https('example.com', 'whatsit/create');
var response = await http.post(url, body: {'name': 'doodle', 'color': 'blue'});
print('Response status: ${response.statusCode}');
print('Response body: ${response.body}');
print(await http.read(Uri.https('example.com', 'foobar.txt')));
}
注意:Flutter 应用程序可能需要额外配置才能进行 HTTP 请求。
使用 Client 发起多次请求
如果你需要向同一个服务器发起多次请求,可以使用 Client
来保持持久连接:
var client = http.Client();
try {
var response = await client.post(
Uri.https('example.com', 'whatsit/create'),
body: {'name': 'doodle', 'color': 'blue'});
var decodedResponse = convert.jsonDecode(utf8.decode(response.bodyBytes)) as Map;
var uri = Uri.parse(decodedResponse['uri'] as String);
print(await client.get(uri));
} finally {
client.close();
}
自定义 Client 行为
你可以通过继承 BaseClient
来添加自定义行为:
class UserAgentClient extends http.BaseClient {
final String userAgent;
final http.Client _inner;
UserAgentClient(this.userAgent, this._inner);
Future<http.StreamedResponse> send(http.BaseRequest request) {
request.headers['user-agent'] = userAgent;
return _inner.send(request);
}
}
重试请求
package:http/retry.dart
提供了 RetryClient
类,可以在请求失败时自动重试:
import 'package:http/http.dart' as http;
import 'package:http/retry.dart';
Future<void> main() async {
final client = RetryClient(http.Client());
try {
print(await client.read(Uri.http('example.org', '')));
} finally {
client.close();
}
}
选择实现
package:http
默认使用 BrowserClient
在 Web 平台上,使用 IOClient
在其他平台上。你也可以根据应用需求选择不同的 Client
实现。
Implementation | Supported Platforms | SDK | Caching | HTTP3/QUIC | Platform Native |
---|---|---|---|---|---|
package:http — IOClient |
Android, iOS, Linux, macOS, Windows | Dart, Flutter | ❌ | ❌ | ❌ |
package:http — BrowserClient |
Web | Dart, Flutter | ― | ✅︎ | ✅︎ |
package:cupertino_http — CupertinoClient |
iOS, macOS | Flutter | ✅︎ | ✅︎ | ✅︎ |
package:cronet_http — CronetClient |
Android | Flutter | ✅︎ | ✅︎ | ― |
package:fetch_client — FetchClient |
Web | Dart, Flutter | ✅︎ | ✅︎ | ✅︎ |
配置
添加依赖
使用 dart pub add
或 flutter pub add
添加 HTTP 客户端依赖:
dart pub add fetch_client
flutter pub add cupertino_http
配置 HTTP 客户端
不同 Client
实现可能需要不同的配置选项。例如:
Client httpClient() {
if (Platform.isAndroid) {
final engine = CronetEngine.build(
cacheMode: CacheMode.memory,
cacheMaxSize: 1000000);
return CronetClient.fromCronetEngine(engine);
}
if (Platform.isIOS || Platform.isMacOS) {
final config = URLSessionConfiguration.ephemeralSessionConfiguration()
..cache = URLCache.withCapacity(memoryCapacity: 1000000);
return CupertinoClient.fromSessionConfiguration(config);
}
return IOClient();
}
连接 HTTP 客户端到代码
将 Client
作为参数传递给需要的地方:
void main() {
final client = httpClient();
fetchAlbum(client, ...);
}
示例代码
以下是一个完整的示例,展示了如何使用 package:http
查询关于 HTTP 的书籍:
import 'dart:convert' as convert;
import 'package:http/http.dart' as http;
void main(List<String> arguments) async {
// This example uses the Google Books API to search for books about http.
// https://developers.google.com/books/docs/overview
var url =
Uri.https('www.googleapis.com', '/books/v1/volumes', {'q': '{http}'});
// Await the http get response, then decode the json-formatted response.
var response = await http.get(url);
if (response.statusCode == 200) {
var jsonResponse =
convert.jsonDecode(response.body) as Map<String, dynamic>;
var itemCount = jsonResponse['totalItems'];
print('Number of books about http: $itemCount.');
} else {
print('Request failed with status: ${response.statusCode}.');
}
}
希望这些信息对你有所帮助!如果你有任何问题或需要进一步的帮助,请随时提问。
更多关于Flutter网络请求插件http的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
1 回复