發起 HTTP 認證授權請求
為了從眾多的網路服務中獲取資料,你需要提供相應的授權認證訊息。當然了,解決這一問題的方法有很多,而最常見的方法或許就是使用 Authorization
HTTP header 了。
新增 Authorization Headers
http
這個 package 提供了相當實用的方法來向請求中新增 headers,你也可以使用 dart:io
來使用一些常見的 HttpHeaders
。
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',
},
);
完整範例
下面的例子是基於 獲取網路資料 中的方法編寫的。
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.'),
};
}
}