发送认证请求
如何从 Web 服务获取已授权的数据。
要从大多数 Web 服务获取数据,你需要提供授权信息。实现方式有很多,但最常见的方式是使用 Authorization HTTP 标头。
添加授权标头
#http 软件包提供了一种向请求添加标头的便捷方法。或者,也可以使用 dart:io 库中的 HttpHeaders 类。
dart
final response = await http.get(
Uri.parse('https://jsonplaceholder.typicode.com/albums/1'),
// Send authorization headers to the backend.
headers: {HttpHeaders.authorizationHeader: 'Basic your_api_token_here'},
);
完整示例
#此示例基于从互联网获取数据的指南构建。
dart
import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'package:http/http.dart' as http;
Future<Album> fetchAlbum() async {
final response = await http.get(
Uri.parse('https://jsonplaceholder.typicode.com/albums/1'),
// Send authorization headers to the backend.
headers: {HttpHeaders.authorizationHeader: 'Basic your_api_token_here'},
);
final responseJson = jsonDecode(response.body) as Map<String, dynamic>;
return Album.fromJson(responseJson);
}
class Album {
final int userId;
final int id;
final String title;
const Album({required this.userId, required this.id, required this.title});
factory Album.fromJson(Map<String, dynamic> json) {
return switch (json) {
{'userId': int userId, 'id': int id, 'title': String title} => Album(
userId: userId,
id: id,
title: title,
),
_ => throw const FormatException('Failed to load album.'),
};
}
}