
创建 HttpClient 实例并设置超时时间为 5 秒。构造目标 URI 并添加自定义请求头后发起 GET 请求,接收响应后需手动处理数据解码:
Future<void> fetchData() async {
final client = HttpClient();
client.idleTimeout = Duration(seconds: 5);
final uri = Uri.parse("https://api.example.com/data");
final request = await client.getUrl(uri);
request.headers.add('user-agent', 'Custom-UA');
final response = await request.close();
if (response.statusCode == HttpStatus.ok) {
final data = await response.transform(utf8.decoder).join();
print(data);
}
}通过 http 包可更简洁地完成网络请求,自动处理连接关闭和编码转换:
dependencies:
http: ^0.13.4Future<void> fetchData() async {
final uri = Uri.parse("https://api.example.com/data");
final response = await http.get(uri, headers: {'user-agent': 'Custom-UA'});
if (response.statusCode == 200) {
print(response.body);
}
}dio 支持拦截器、文件传输等高级特性,需先添加依赖:
dependencies:
dio: ^4.0.0基础请求示例
final dio = Dio();
final response = await dio.get(
'https://api.example.com/data',
options: Options(headers: {'user-agent': 'Custom-UA'})
);文件上传实现
final formData = FormData.fromMap({
'file': await MultipartFile.fromFile('path/to/file.txt')
});
await dio.post('https://upload.example.com', data: formData);并发请求处理
final responses = await Future.wait([
dio.get('https://api1.example.com'),
dio.post('https://api2.example.com')
]);拦截器配置
dio.interceptors.add(InterceptorsWrapper(
onRequest: (options, handler) {
options.headers['token'] = 'auth_token';
return handler.next(options);
}
));对于 JSON 格式响应,推荐使用 jsonDecode 进行解析:
final Map<String, dynamic> data = jsonDecode(response.body);
print(data['key']);对于大型文件下载,建议使用分块处理:
await dio.download(
'https://example.com/largefile.zip',
'local/path.zip',
onReceiveProgress: (received, total) {
print('${(received/total*100).toStringAsFixed(0)}%');
}
);