扑扑的HTTP请求

kar*_*i j 10 android dart retrofit flutter

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

Sur*_*gch 30

如何在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
Run Code Online (Sandbox Code Playgroud)

设定

pubspec.yaml中添加http包依赖

dependencies:
  http: ^0.12.0+1
Run Code Online (Sandbox Code Playgroud)

GET请求

_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字符串转换为对象。

POST请求

_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)

有关