我必须将 API key 放在请求 header 中:
Authorization: Bearer "YOUR API KEY"
这是我的代码( 我不确定在哪里放置标题以及如何放置 )
Future<Stream<Book>> getBooks() async {
var url = ‘example_url’
var client = http.Client();
var streamedResponse = await client.send(
http.Request(‘get’, Uri.parse(url))
);
return streamedResponse.stream
.transform(utf.decoder)
.transform(json.decoder)
.expand(jsonBody) => (jsonBody as Map)[‘results’] )
.map((jsonBook) = Book.fromJson(jsonBook));
}
Flutter 文档 https://flutter.io/cookbook/networking/authenticated-requests/说要将此格式用于经过身份验证的请求,但这不适用于流,这将返回对象的 future (书)
Future<Book> fetchPost() async {
final response = await http.get(
'https://jsonplaceholder.typicode.com/posts/1',
headers: {HttpHeaders.authorizationHeader: "Place your_api_token_here"},
);
final responseJson = json.decode(response.body);
return Book.fromJson(responseJson);
}
最佳答案
您可以在创建 Request
后添加自定义标题。
final request = http.Request('GET'), url)
..headers.addAll(myHeaders);
关于mobile - 如何发出经过身份验证的 http 请求并返回带有 dart 的对象流?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52923567/