我正在使用 Retrofit for Android。通过基于 REST 的 Web 服务很容易检索和上传 JSON。在 Flutter 中我们能得到任何相当于 Retrofit for web services 的库吗?
最佳答案
本来我是先在这里写答案的,后来写了一篇更详细的帖子:
完整的源代码也在那里。
这个答案告诉如何使用 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
_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 字符串转换为对象。
_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 请求旨在替换资源或在资源不存在时创建它。
_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",
};
https://stackoverflow.com/questions/54360761/