扑朔迷离的HTTP请求 [英] HTTP request in flutter
问题描述
我正在使用Android的Retrofit.通过基于REST的Web服务可以很容易地检索和上传JSON.我们可以在Flutter中获得与Web服务的Retrofit等效的任何库吗?
I am using Retrofit for Android. It is easy to retrieve and upload JSON via a REST based web service. Can we get any library which is equivalent to Retrofit for web services in Flutter?
推荐答案
如何在Flutter中发出HTTP请求
此答案说明了Dart团队如何使用 http程序包发出HTTP请求.如果需要更多高级功能,请查看注释中提到的 Dio软件包.
How to make HTTP requests in Flutter
This answer tells how to make HTTP requests using the http package by the Dart team. If more advanced functionality is needed, check out the Dio package mentioned in the comments.
我们将使用 JSONPlaceholder 作为我们下面的API示例的目标.
We will be using JSONPlaceholder as a target for our API examples below.
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包依赖项.
Setup
Add the http package dependency in pubspec.yaml.
dependencies:
http: ^0.12.0+1
获取请求
_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...
}
用/posts/1
和上面提到的其他GET请求替换/posts
.使用posts
返回JSON对象数组,而/posts/1
返回单个JSON对象.您可以使用 dart:convert 将原始JSON字符串转换为对象.
Replace /posts
with /posts/1
and the other GET requests mentioned above. Using posts
returns an array of JSON objects while /posts/1
returns a single JSON object. You can use dart:convert to convert the raw JSON string to objects.
_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
// }
}
PUT请求
PUT请求旨在替换资源或在不存在的情况下创建资源.
PUT request
A PUT request is meant to replace a resource or create it if it doesn't exist.
_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
// }
}
PATCH请求
PATCH请求旨在修改现有资源.
PATCH request
A PATCH request is meant to modify a existing resource.
_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)",
// }
}
请注意,传入的JSON字符串仅包含标题,而不包含PUT示例中的其他部分.
Notice that the JSON string that is passed in only includes the title, not the other parts like in the PUT example.
_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;
}
身份验证
尽管我们上面使用的演示站点不需要它,但是如果您需要包括身份验证标头,则可以这样做:
Authentication
Although the demo site we used above did not require it, if you need to include authentication headers, you can do it like this:
基本身份验证
// 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",
};
承载者(令牌)身份验证
Bearer (token) Authentication
// import 'dart:io';
final token = 'WIiOiIxMjM0NTY3ODkwIiwibmFtZSI6Ikpv';
Map<String, String> headers = {
HttpHeaders.contentTypeHeader: "application/json", // or whatever
HttpHeaders.authorizationHeader: "Bearer $token",
};
相关
- PUT,POST和PATCH有什么区别?
- What is the difference between PUT, POST and PATCH?
Related
这篇关于扑朔迷离的HTTP请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!