Flutter网络请求Android iOS运行真正的跨平台

此答案说明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网络请求你学会了吗?

欢迎点赞,关注,我才有动力继续写下去。

Flutter网络请求Android iOS运行真正的跨平台

展开阅读全文

页面更新:2024-04-24

标签:网络   示例   框架   网路   接口   对象   团队   状态   答案   参数   简单   动力   格式   文件   项目   数码   平台

1 2 3 4 5

上滑加载更多 ↓
推荐阅读:
友情链接:
更多:

本站资料均由网友自行发布提供,仅用于学习交流。如有版权问题,请与我联系,QQ:4156828  

© CopyRight 2020-2024 All Rights Reserved. Powered By 71396.com 闽ICP备11008920号-4
闽公网安备35020302034903号

Top