颤振中的 HTTP 请求

新手上路,请多包涵

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

原文由 kartheeki j 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 281
2 个回答

更新

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

完整的源代码也在那里。

如何在 Flutter 中发起 HTTP 请求

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

我们将使用 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",
};

承载(令牌)认证

// import 'dart:io';

final token = 'WIiOiIxMjM0NTY3ODkwIiwibmFtZSI6Ikpv';

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

有关的

原文由 Suragch 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题