傳送認證請求
要從大多數 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.'),
};
}
}