Как сделать HTTP-запросы во флаттере
Этот ответ говорит о том, как сделать HTTP-запросы с помощью http пакета командой Dart. Если требуется более продвинутая функциональность, проверьте пакет 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
Настройка
Добавить зависимость пакета http в pubspec.yaml .
dependencies:
http: ^0.12.0+1
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...
}
Заменить /posts
на /posts/1
и другие GET-запросы, упомянутые выше. Использование 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
// }
}
запрос PUT
Запрос 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
// }
}
запрос PATCH
Запрос 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)",
// }
}
Обратите внимание, что передаваемая строка 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;
}
* * Аутентификация тысяча сорок-девять
Хотя демонстрационный сайт, который мы использовали выше, не требовал этого, если вам нужно включить заголовки аутентификации, вы можете сделать это следующим образом:
Базовая аутентификация
// 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",
};
Аутентификация на носителе (токене)
// import 'dart:io';
final token = 'WIiOiIxMjM0NTY3ODkwIiwibmFtZSI6Ikpv';
Map<String, String> headers = {
HttpHeaders.contentTypeHeader: "application/json", // or whatever
HttpHeaders.authorizationHeader: "Bearer $token",
};
Относящиеся