Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
203 views
in Technique[技术] by (71.8m points)

android - HTTP request in flutter

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Update

Originally I wrote the answer here first, but I ended up writing a more detailed post later:

The full source code is there, too.

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.

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

Setup

Add the http package dependency in pubspec.yaml.

dependencies:
  http: ^0.12.0+1

GET requests

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

}

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.

POST request

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

A PATCH request is meant to modify a existing resource.

_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
suscipit recusandae... (old body text not changed)",
  // }

}

Notice that the JSON string that is passed in only includes the title, not the other parts like in the PUT example.

DELETE request

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

}

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:

Basic Authentication

// 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",
};

Bearer (token) Authentication

// import 'dart:io';

final token = 'WIiOiIxMjM0NTY3ODkwIiwibmFtZSI6Ikpv';

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

Related


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...