为了从更多的Web服务获取数据,有些时候您需要提供授权。有很多方法可以做到这一点,但最常见的可能是使用HTTP header中的Authorization

注:本篇示例官方使用的是用http package发起简单的网络请求,但是http package功能较弱,很多功能都不支持。我们建议您使用dio 来发起网络请求,它是一个强大易用的dart http请求库,支持Restful API、FormData、拦截器、请求取消、Cookie管理、文件上传/下载……详情请查看github dio .

添加 Authorization Headers

http package提供了一种方便的方法来为请求添加headers。您也可以使用dart:iopackage来添加。

  1. Future<http.Response> fetchPost() {
  2. return http.get(
  3. 'https://jsonplaceholder.typicode.com/posts/1',
  4. // Send authorization headers to your backend
  5. headers: {HttpHeaders.AUTHORIZATION: "Basic your_api_token_here"},
  6. );
  7. }

完整的例子

这个例子建立在从互联网上获取数据之上 。

  1. import 'dart:async';
  2. import 'dart:convert';
  3. import 'dart:io';
  4. import 'package:http/http.dart' as http;
  5. Future<Post> fetchPost() async {
  6. final response = await http.get(
  7. 'https://jsonplaceholder.typicode.com/posts/1',
  8. headers: {HttpHeaders.AUTHORIZATION: "Basic your_api_token_here"},
  9. );
  10. final json = JSON.decode(response.body);
  11. return new Post.fromJson(json);
  12. }
  13. class Post {
  14. final int userId;
  15. final int id;
  16. final String title;
  17. final String body;
  18. Post({this.userId, this.id, this.title, this.body});
  19. factory Post.fromJson(Map<String, dynamic> json) {
  20. return new Post(
  21. userId: json['userId'],
  22. id: json['id'],
  23. title: json['title'],
  24. body: json['body'],
  25. );
  26. }
  27. }