Dart HTTP GET/POST 请求
最后修改日期:2024 年 1 月 28 日
在本文中,我们将展示如何在 Dart 中发送 GET 和 POST 请求。
HTTP
超文本传输协议(Hypertext Transfer Protocol (HTTP))是一种用于分布式、协作式、超媒体信息系统的应用层协议。HTTP 协议是万维网数据通信的基础。
在代码示例中,我们使用了 httpbin.org
,这是一个免费的 HTTP 请求和响应服务,以及 webcode.me
,这是一个用于测试的小型 HTML 页面。
HTTP GET
HTTP GET 方法请求指定资源的表示。使用 GET 的请求应该只检索数据。
HTTP POST
HTTP POST 方法将数据发送到服务器。它通常用于上传文件或提交完成的 Web 表单。
Dart http
http
是一个可组合的、基于 Future 的库,用于发出 HTTP 请求。
$ dart pub add http
我们添加 http
包。
name: app environment: sdk: '>=2.18.0 <3.0.0' dependencies: http: ^0.13.5
这是 pubspec.yaml
。
Dart GET 请求
以下示例在 Dart 中创建了一个简单的 GET 请求。
import 'package:http/http.dart' as http; Future<String> fetchData() async { final resp = await http.get(Uri.http('webcode.me')); if (resp.statusCode == 200) { return resp.body; } else { throw Exception('Failed to fetch data'); } } void main() async { var data = await fetchData(); print(data); }
在示例中,我们向 webcode.me 发送了一个 GET 请求,并打印了响应体。
import 'package:http/http.dart' as http;
导入了 http
包。
Future<String> fetchData() async {
fetchData
是一个异步函数,它返回一个 future。
final resp = await http.get(Uri.http('webcode.me'));
使用 http.get
创建 GET 请求。await
关键字获取异步操作的已完成结果。
if (resp.statusCode == 200) { return resp.body; } else { throw Exception('Failed to fetch data'); }
如果响应状态码为成功,我们返回响应体。
$ dart main.dart <!DOCTYPE html> <html lang="en"> <head>
Dart GET 带 User Agent
User-Agent 请求标头是一个字符串,允许服务器和网络对等方识别请求用户代理的应用程序、操作系统、供应商和/或版本。
import 'package:http/http.dart' as http; Future<String> fetchData() async { final resp = await http.get(Uri.parse('http://webcode.me/ua.php'), headers: <String, String>{ 'User-Agent': 'Dart program', }); return resp.body; } void main() async { var data = await fetchData(); print(data); }
在 GET 请求中,我们包含了 User-Agent
头。指定的 URL 仅返回 User-Agent 字符串。
final resp = await http.get(Uri.parse('http://webcode.me/ua.php'), headers: <String, String>{ 'User-Agent': 'Dart program', });
http.get
的第二个参数是 headers 映射,我们在其中包含 User-Agent
头。
$ dart main.dart Dart program
Dart HTTP POST 请求 JSON 数据
以下示例发送了一个带有 JSON 格式数据的 POST 请求。
import 'dart:convert'; import 'package:http/http.dart' as http; Future<http.Response> doPost() { return http.post( Uri.parse('http://httpbin.org/post'), headers: <String, String>{ 'Content-Type': 'application/json; charset=UTF-8', }, body: jsonEncode(<String, String>{ 'name': 'John Doe', 'occupation': 'gardener' }), ); } void main() async { var user = await doPost(); print(user.body); }
我们向 httpbin.org/post 网页生成了一个 POST 请求。数据使用 jsonEncode
编码为 JSON。
return http.post(
使用 http.post
创建 POST 请求。
headers: <String, String>{ 'Content-Type': 'application/json; charset=UTF-8', },
我们将 Content-Type
设置为 application/json
。
$ dart main.dart { "args": {}, "data": "{\"name\":\"John Doe\",\"occupation\":\"gardener\"}", "files": {}, "form": {}, "headers": { "Accept-Encoding": "gzip", "Content-Length": "43", "Content-Type": "application/json; charset=UTF-8", "Host": "httpbin.org", "User-Agent": "Dart/2.18 (dart:io)", "X-Amzn-Trace-Id": "Root=1-63171a73-079b3a3c741be7087ae50902" }, "json": { "name": "John Doe", "occupation": "gardener" }, ... "url": "http://httpbin.org/post" }
Dart HTTP POST 请求 FORM 数据
对于 POST 表单请求,数据在请求体中进行 URL 编码。Content-Type 头设置为 application/x-www-form-urlencoded
。数据发送在请求体中;键和值被编码为由 '&' 分隔的键值对,键和值之间用 '=' 分隔。
import 'package:http/http.dart' as http; Future<http.Response> doPost() { return http.post(Uri.parse('https://httpbin.org/post'), headers: <String, String>{ 'Content-Type': 'application/x-www-form-urlencoded', }, body: "name=John%20Doe&occupation=gardener"); } void main() async { var user = await doPost(); print(user.body); }
我们向 https://httpbin.org/post 页面发送了一个 POST FORM 请求。
headers: <String, String>{ 'Content-Type': 'application/x-www-form-urlencoded', },
内容类型设置为 application/x-www-form-urlencoded
。
body: "name=John%20Doe&occupation=gardener");
数据在请求体中进行 URL 编码。
$ dart main.dart { "args": {}, "data": "", "files": {}, "form": { "name": "John Doe", "occupation": "gardener" }, "headers": { "Accept-Encoding": "gzip", "Content-Length": "35", "Content-Type": "application/x-www-form-urlencoded; charset=utf-8", "Host": "httpbin.org", "User-Agent": "Dart/2.18 (dart:io)", "X-Amzn-Trace-Id": "Root=1-63171ba3-0ee639310c8b5040773c366b" }, "json": null, ... "url": "https://httpbin.org/post" }
来源
在本文中,我们创建了 Dart 中的 GET 和 POST 请求。
作者
列出 所有 Dart 教程。