如何在 Flutter 中的 Streamed 请求(发送)中发送授权标头数据

问题描述 投票:0回答:2

如何在 Flutter 中的 Streamed 请求(发送)中发送授权标头数据:
我需要将

HttpHeaders.authorizationHeader: 'Bearer $_apiToken'
添加到请求标头

try {
    final client = new http.Client();
    final streamedRest = await client.send(http.Request('get', uri));

    return streamedRest.stream
        .transform(utf8.decoder)
        .transform(json.decoder)
        .map((data) => Helper.getData(data))
        .expand((data) => (data as List))
        .map((data) => Category.fromJSON(data));
  } catch (e) {
    print(CustomTrace(StackTrace.current, message: uri.toString()).toString());
    return new Stream.value(new Category.fromJSON({}));
  }

请问有什么帮助吗?

flutter httprequest
2个回答
0
投票
try {
    final client = new http.Client();
    final streamedRest = await client.get(url, // Your API endpoint
          headers: {
            'authorization': "Token $_Token"
          });
    return streamedRest.stream
        .transform(utf8.decoder)
        .transform(json.decoder)
        .map((data) => Helper.getData(data))
        .expand((data) => (data as List))
        .map((data) => Category.fromJSON(data));
  } catch (e) {
    print(CustomTrace(StackTrace.current, message: uri.toString()).toString());
    return new Stream.value(new Category.fromJSON({}));
  }

请尝试这样。


0
投票
final url = Uri.parse('uri');
final client = http.Client();

try {
//headers and body
  final request = http.Request('POST', url)
    ..headers['accept'] = 'text/plain'
    ..headers['Content-Type'] = 'application/json'
    ..body = jsonEncode(message.toMap());

  final response = await client.send(request);

  // Read and print the chunks from the response stream
  await for (var chunk in response.stream.transform(utf8.decoder)) {
    // Process each chunk as it is received
    print(chunk);
  }

} catch (e) {
  print("Error: $e");
} finally {
  client.close();
}

}

© www.soinside.com 2019 - 2024. All rights reserved.