Sur*_*gch 30
此答案说明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
Run Code Online (Sandbox Code Playgroud)
在pubspec.yaml中添加http包依赖项。
dependencies:
http: ^0.12.0+1
Run Code Online (Sandbox Code Playgroud)
_makeGetRequest() async {
// make request
Response response = await get('https://jsonplaceholder.typicode.com/posts');
// sample info available in response
int statusCode = response.statusCode;
Map<String, String> headers = response.headers;
String contentType = headers['content-type'];
String json = response.body;
// TODO convert json to object...
}
Run Code Online (Sandbox Code Playgroud)
替换/posts为/posts/1和上面提到的其他GET请求。using posts返回JSON对象数组,而/posts/1返回单个JSON对象。您可以使用dart:convert将原始JSON字符串转换为对象。
_makePostRequest() async {
// set up POST request arguments
String url = 'https://jsonplaceholder.typicode.com/posts';
Map<String, String> headers = {"Content-type": "application/json"};
String json = '{"title": "Hello", "body": "body text", "userId": 1}';
// make POST request
Response response = await post(url, headers: headers, body: json);
// check the status code for the result
int statusCode = response.statusCode;
// this API passes back the id of the new item added to the body
String body = response.body;
// {
// "title": "Hello",
// "body": "body text",
// "userId": 1,
// "id": 101
// }
}
Run Code Online (Sandbox Code Playgroud)
PUT请求用于替换资源或在不存在的情况下创建资源。
_makePutRequest() async {
// set up PUT request arguments
String url = 'https://jsonplaceholder.typicode.com/posts/1';
Map<String, String> headers = {"Content-type": "application/json"};
String json = '{"title": "Hello", "body": "body text", "userId": 1}';
// make PUT request
Response response = await put(url, headers: headers, body: json);
// check the status code for the result
int statusCode = response.statusCode;
// this API passes back the updated item with the id added
String body = response.body;
// {
// "title": "Hello",
// "body": "body text",
// "userId": 1,
// "id": 1
// }
}
Run Code Online (Sandbox Code Playgroud)
PATCH请求旨在修改现有资源。
_makePatchRequest() async {
// set up PATCH request arguments
String url = 'https://jsonplaceholder.typicode.com/posts/1';
Map<String, String> headers = {"Content-type": "application/json"};
String json = '{"title": "Hello"}';
// make PATCH request
Response response = await patch(url, headers: headers, body: json);
// check the status code for the result
int statusCode = response.statusCode;
// only the title is updated
String body = response.body;
// {
// "userId": 1,
// "id": 1
// "title": "Hello",
// "body": "quia et suscipit\nsuscipit recusandae... (old body text not changed)",
// }
}
Run Code Online (Sandbox Code Playgroud)
请注意,传入的JSON字符串仅包含标题,而不包括PUT示例中的其他部分。
_makeDeleteRequest() async {
// post 1
String url = 'https://jsonplaceholder.typicode.com/posts/1';
// make DELETE request
Response response = await delete(url);
// check the status code for the result
int statusCode = response.statusCode;
}
Run Code Online (Sandbox Code Playgroud)
尽管我们上面使用的演示站点不需要它,但是如果您需要包括身份验证标头,则可以这样进行:
基本认证
// import 'dart:convert'
final username = 'username';
final password = 'password';
final credentials = '$username:$password';
final stringToBase64Url = utf8.fuse(base64Url);
final encodedCredentials = stringToBase64Url.encode(credentials);
Map<String, String> headers = {
HttpHeaders.contentTypeHeader: "application/json", // or whatever
HttpHeaders.authorizationHeader: "Basic $encodedCredentials",
};
Run Code Online (Sandbox Code Playgroud)
承载(令牌)认证
// import 'dart:io';
final token = 'WIiOiIxMjM0NTY3ODkwIiwibmFtZSI6Ikpv';
Map<String, String> headers = {
HttpHeaders.contentTypeHeader: "application/json", // or whatever
HttpHeaders.authorizationHeader: "Bearer $token",
};
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
10512 次 |
| 最近记录: |