android - Flutter 中的 HTTP 请求

我正在使用 Retrofit for Android。通过基于 REST 的 Web 服务很容易检索和上传 JSON。在 Flutter 中我们能得到任何相当于 Retrofit for web services 的库吗?

最佳答案

更新

本来我是先在这里写答案的,后来写了一篇更详细的帖子:

  • How to make HTTP requests in Flutter

完整的源代码也在那里。

如何在 Flutter 中发出 HTTP 请求

这个答案告诉如何使用 http package 发出 HTTP 请求。由 Dart 队。如果需要更高级的功能,请查看 Dio package评论中提到了。

我们将使用 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

设置

pubspec.yaml中添加http包依赖。

dependencies:
  http: ^0.12.0+1

GET 请求

_makeGetRequest() async {

  // make request
  final response = await get(Uri.parse('https://jsonplaceholder.typicode.com/posts'));
  
  // sample info available in response
  final statusCode = response.statusCode;
  final headers = response.headers;
  final contentType = headers['content-type'];
  final json = response.body;

  // TODO convert json to object...

}

/posts 替换为 /posts/1 和上面提到的其他 GET 请求。使用 posts 返回 JSON 对象数组,而 /posts/1 返回单个 JSON 对象。您可以使用dart:convert将原始 JSON 字符串转换为对象。

POST 请求

_makePostRequest() async {
  
  // set up POST request arguments
  final url = Uri.parse('https://jsonplaceholder.typicode.com/posts');
  final headers = {"Content-type": "application/json"};
  final json = '{"title": "Hello", "body": "body text", "userId": 1}';

  // make POST request
  final response = await post(url, headers: headers, body: json);

  // check the status code for the result
  final statusCode = response.statusCode;
  
  // this API passes back the id of the new item added to the body
  final body = response.body;
  // {
  //   "title": "Hello",
  //   "body": "body text",
  //   "userId": 1,
  //   "id": 101
  // }

}

PUT 请求

PUT 请求旨在替换资源或在资源不存在时创建它。

_makePutRequest() async {

  // set up PUT request arguments
  final url = Uri.parse('https://jsonplaceholder.typicode.com/posts/1');
  final headers = {"Content-type": "application/json"};
  final json = '{"title": "Hello", "body": "body text", "userId": 1}';

  // make PUT request
  final response = await put(url, headers: headers, body: json);

  // check the status code for the result
  final statusCode = response.statusCode;

  // this API passes back the updated item with the id added
  final body = response.body;
  // {
  //   "title": "Hello",
  //   "body": "body text",
  //   "userId": 1,
  //   "id": 1
  // }

}

补丁请求

PATCH 请求旨在修改现有资源。

_makePatchRequest() async {

  // set up PATCH request arguments
  final url = Uri.parse('https://jsonplaceholder.typicode.com/posts/1');
  final headers = {"Content-type": "application/json"};
  final json = '{"title": "Hello"}';

  // make PATCH request
  final response = await patch(url, headers: headers, body: json);

  // check the status code for the result
  final statusCode = response.statusCode;

  // only the title is updated
  final body = response.body;
  // {
  //   "userId": 1,
  //   "id": 1
  //   "title": "Hello",
  //   "body": "quia et suscipit\nsuscipit recusandae... (old body text not changed)",
  // }

}

请注意,传入的 JSON 字符串仅包括标题,而不包括 PUT 示例中的其他部分。

删除请求

_makeDeleteRequest() async {

  // post 1
  final url = Uri.parse('https://jsonplaceholder.typicode.com/posts/1');

  // make DELETE request
  final response = await delete(url);

  // check the status code for the result
  final statusCode = response.statusCode;

}

认证

虽然我们上面使用的演示站点不需要它,但如果你需要包含身份验证头,你可以这样做:

基本认证

// import 'dart:convert'

final username = 'username';
final password = 'password';
final credentials = '$username:$password';
final stringToBase64Url = utf8.fuse(base64Url);
final encodedCredentials = stringToBase64Url.encode(credentials);

final headers = {
  HttpHeaders.contentTypeHeader: "application/json", // or whatever
  HttpHeaders.authorizationHeader: "Basic $encodedCredentials",
};

承载( token )身份验证

// import 'dart:io';

final token = 'WIiOiIxMjM0NTY3ODkwIiwibmFtZSI6Ikpv';

final headers = {
  HttpHeaders.contentTypeHeader: "application/json", // or whatever
  HttpHeaders.authorizationHeader: "Bearer $token",
};

相关

  • What is the difference between PUT, POST and PATCH?

https://stackoverflow.com/questions/54360761/

相关文章:

Flutter:多语言应用程序 - 如何覆盖语言环境?

flutter - 无状态和有状态小部件有什么区别?

dart - 每 x 秒 flutter 一次运行功能

flutter - 有没有更好的方法来检查#flutter 中的左/右拖动?

dart - flutter 垂直视口(viewport)无界高度错误

dart - 自动调用 ListView 上的按钮的 Flutter onPressed(当它变得可

flutter - 在 ListTile 中放置两个尾随图标

google-maps - Flutter中的谷歌地图没有响应触摸事件

firebase - 如何从 Flutter 中的 UploadTaskSnapshot 获取完整的

flutter - 在 Flutter 中使用 Google 登录的错误 403 受限客户端