傳送認證請求
如何從 Web 服務獲取授權資料。
要從大多數 Web 服務獲取資料,您需要提供授權。實現方式有很多,但最常見的是使用 Authorization HTTP 頭。
新增授權頭
#http 包提供了一種方便的方法來將頭資訊新增到您的請求中。或者,您可以使用 HttpHeaders 類,該類來自 dart:io 庫。
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.'),
};
}
}