Published on

flutter 接收http流

Authors
    final req = http.Request("POST",
        Uri.parse("http://you.com/api"));
    req.headers.addAll({
      'Content-Type': 'application/json; charset=UTF-8',
      'User-Agent':
          'Mozilla/5.0 ..... '
    });
    req.body = reqBody;
    final rsp = await req.send();
    await for (final chunk in rsp.stream.transform(utf8.decoder)) {
      //do something with data.
    }

另一种方法:

Stream<String> connect(
  String path, {
  Map<String, dynamic>? headers,
  required String body,
}) {
  int progress = 0;
  final httpRequest = HttpRequest();
  final streamController = StreamController<String>();
  httpRequest.open('POST', 'your url');
  headers?.forEach((key, value) {
    httpRequest.setRequestHeader(key, value);
  });
  httpRequest.addEventListener('progress', (event) {
    final data = httpRequest.responseText!.substring(progress);
    progress += data.length;
    streamController.add(data);
  });
  httpRequest.addEventListener('loadend', (event) {
    httpRequest.abort();
    streamController.close();
  });
  httpRequest.addEventListener('error', (event) {
    streamController.addError(
      httpRequest.responseText ?? httpRequest.status ?? 'err',
    );
  });
  httpRequest.send(body);
  return streamController.stream;
}

https://github.com/dart-lang/http/issues/337#issuecomment-1564031391