Flutter网络请求AndroidiOS运行真正的跨平台
此答案说明Dart团队如何使用http包发出HTTP请求,
我们将使用JSONPlaceholder作为API示例,大家可以看看格式如下GET / posts GET / posts / 1 GET / posts / 1 / comments GET / comments?postId = 1 GET / posts?userId = 1 POST / posts PUT / posts / 1 PATCH / posts / 1 DELETE / posts / 1
我们先来添加一个网络请求框架到项目里面dependencies: http: ^0.12.0+4
当我们要在项目文件里面使用网路的时候,需要导入这个框架的API包:import "package:http/http.dart";
接下来我写个简单的API请求,GET请求,大家可以看看_makeGetRequest() async { String url = "https://jsonplaceholder.typicode.com/posts"; Response response = await get(url); int statusCode = response.statusCode; Map headers = response.headers; String contentType = headers["content-type"]; String json = response.body; }
可以使用dart:convert将接口返回的数据转换成你想要的对象。_makePostRequest() async { // 设置POST请求参数 String url = "https://jsonplaceholder.typicode.com/posts"; Map headers = {"Content-type": "application/json"}; String json = "{"title": "Hello", "body": "body text", "userId": 1}"; // 发出POST请求 Response response = await post(url, headers: headers, body: json); // 检查结果的状态码 int statusCode = response.statusCode; String body = response.body; // { // "title": "Hello", // "body": "body text", // "userId": 1, // "id": 101 // } }
这节课就讲解到这里吧,一个简单的get,post请求就完成了,Flutter网络请求你学会了吗?
欢迎点赞,关注,我才有动力继续写下去。