Flutter 通过HttpClient发起HTTP请求
封面图
•
2025-11-14
•
Flutter
0
0
0
0
在 Flutter 中,你可以使用 `dart:io` 库中的 `HttpClient` 来发起 HTTP 请求。虽然现在更推荐使用 `http` 或 `dio` 这样的第三方库(因为它们更简洁、功能更强大),但如果你希望直接使用 `HttpClient`,下面是一个基本的示例。 --- ## ✅ 使用 `HttpClient` 发起 GET 请求 ```dart import 'dart:io'; import 'dart:convert'; void main() async { // 创建 HttpClient 实例 final httpClient = HttpClient(); try { // 发起 GET 请求 final request = await httpClient.getUrl(Uri.parse('https://jsonplaceholder.typicode.com/posts/1')); // 发送请求并获取响应 final response = await request.close(); // 读取响应体 final responseBody = await response.transform(utf8.decoder).join(); print('Response status code: ${response.statusCode}'); print('Response body: $responseBody'); } catch (e) { print('Error: $e'); } finally { // 关闭 HttpClient httpClient.close(); } } ``` --- ## 🚀 使用 `HttpClient` 发起 POST 请求 ```dart import 'dart:io'; import 'dart:convert'; void main() async { final httpClient = HttpClient(); try { final request = await httpClient.postUrl(Uri.parse('https://jsonplaceholder.typicode.com/posts')); // 设置请求头 request.headers.contentType = ContentType.json; // 设置请求体 final body = jsonEncode({ 'title': 'foo', 'body': 'bar', 'userId': 1, }); request.write(body); // 发送请求并获取响应 final response = await request.close(); final responseBody = await response.transform(utf8.decoder).join(); print('Status code: ${response.statusCode}'); print('Response body: $responseBody'); } catch (e) { print('Error: $e'); } finally { httpClient.close(); } } ``` --- ## ⚠️ 注意事项 - `HttpClient` 是 `dart:io` 的一部分,因此它**仅适用于 Flutter 的桌面或移动端应用**,不适用于 Web。 - 如果你希望支持 Web 平台,建议使用 `http` 或 `dio` 等跨平台库。 - `HttpClient` 在 Flutter 中可能会因平台差异而表现不同,特别是在 Android 上可能需要额外配置。 --- ## 📦 推荐替代方案:使用 `http` 包 如果你希望代码更简洁、兼容性更好,可以使用 `http` 包: ### 添加依赖: ```yaml dependencies: http: ^0.13.5 ``` ### 示例 GET 请求: ```dart import 'package:http/http.dart' as http; void main() async { final response = await http.get(Uri.parse('https://jsonplaceholder.typicode.com/posts/1')); if (response.statusCode == 200) { print(response.body); } else { print('Request failed with status: ${response.statusCode}'); } } ``` --- ## ✅ 总结 | 功能 | `HttpClient` | `http` 包 | |------|--------------|-----------| | 是否推荐 | 不推荐(复杂) | 推荐(简单、跨平台) | | 是否支持 Web | ❌ | ✅ | | 是否需要关闭连接 | ✅ | ❌(自动管理) | --- 如果你需要更高级的功能(如拦截器、超时设置等),建议使用 `dio` 或 `http`。如果只是简单的用法,`HttpClient` 也可以胜任。需要我帮你写一个完整的 Flutter 示例吗?
上一篇:
Flutter 文件操作
下一篇:
iOS开发 定位操作
标题录入,一次不能超过6条
留言
评论