如何发出经过身份验证的http请求并使用dart返回对象流?

时间:2018-10-22 06:38:42

标签: mobile dart http-headers flutter http-get

我必须将API密钥放在请求标头中为

  

授权:承载“您的API密钥”

这是我的代码(我不确定将标头放在何处以及如何放置

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<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);
}

2 个答案:

答案 0 :(得分:2)

我使用http.Request创建了一个自定义标头,如下所示:

final url =
    'https://cdimage.debian.org/debian-cd/current/amd64/iso-cd/debian-10.6.0-amd64-xfce-CD-1.iso';
final request = Request('GET', Uri.parse(url));
request.headers.clear();
request.headers.addAll({"content-type":"application/json"});

答案 1 :(得分:1)

创建Request

后,可以添加自定义标题
final request = http.Request('GET'), url)
      ..headers.addAll(myHeaders);