Flutter http streamedResponse.stream和streamedResponse.sink [英] Flutter http streamedResponse.stream and streamedResponse.sink

查看:503
本文介绍了Flutter http streamedResponse.stream和streamedResponse.sink的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习Flutter http软件包的第三个示例,这是代码的基础: https://pub.dev/packages/http

I'm learning the third example of Flutter http package, this is the base of the code: https://pub.dev/packages/http

通过BaseClient.send发送请求时,将仅发送标头和已写入 StreamedRequest.stream 的所有数据.一旦将数据写入 StreamedRequest.sink ,就会发送更多数据,当接收器关闭时,请求将结束.

When the request is sent via BaseClient.send, only the headers and whatever data has already been written to StreamedRequest.stream will be sent immediately. More data will be sent as soon as it's written to StreamedRequest.sink, and when the sink is closed the request will end.

https://pub.dev/documentation/http/latest /http/StreamedRequest-class.html

  1. 从文档中,我不了解我们应该如何写入StreamedRequest.stream? (立即发送数据)

  1. From the docs, I don't understand how we should write to StreamedRequest.stream? (To send data immediately)

StreamedResponse.sink基本上不是我们在其中添加HTTP POST的请求正文的地方:为什么它仅接受List<int>?不应该是Map<String, String>吗?如果不是,那么我们应该在哪里添加请求主体? NEW:即使我使用ut8.encode对其进行编码,但在调试时它仍未显示在Fiddler的WebForms上,如何正确发送x-www-form-urlencoded?:

Isn't StreamedResponse.sink basically where we add our HTTP POST's Request Body: Why does it only accept a List<int>? Shouldn't it be a Map<String, String>? If it's not then where should we add the request body? NEW: Even when I encode it with ut8.encode, it still doesn't show up on Fiddler's WebForms when I'm debugging, how do I send a x-www-form-urlencoded properly?:

代码:

userAgentClient = UserAgentClient(userAgent, client);
streamedRequest = http.StreamedRequest('POST', Uri(scheme: 'http', path: '/posts/', host: 'jsonplaceholder.typicode.com'));
streamedRequest.sink.add([123, 456]); // It has to be a List<int>

//NEW:
streamedRequest.sink.add(utf8.encode('username=123&password=456'));
streamedRequest.sink.add(utf8.encode('{"username":"123","password":"456"}'));

  1. 为什么必须关闭接收器才能访问StreamedResponse的属性?

streamedRequest.sink.close();

更新:

class UserAgentClient extends http.BaseClient {
  final String userAgent;
  final http.Client client;
  UserAgentClient(this.userAgent, this.client);
  Future<http.StreamedResponse> send(http.BaseRequest request){
    request.headers['user-agent'] = userAgent;
    return client.send(request);
  }
}

dynamic _status = '';
dynamic _body = '';
dynamic _headers = '';
String _reason = '';
http.Client client = http.Client();
String userAgent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.121 Safari/537.36';
UserAgentClient userAgentClient;
http.StreamedRequest streamedRequest;

void _httpStreamed(){
  userAgentClient = UserAgentClient(userAgent, client);
  streamedRequest = http.StreamedRequest('POST', Uri(scheme: 'http', path: '/posts/', host: 'jsonplaceholder.typicode.com'));
  streamedRequest.sink.add(utf8.encode('{"username":"123","password":"456"}'));
  setState(() {
    _status = streamedRequest.url;
    _body = '';
    _headers = '';
    _reason = '';
  });
}

void _httpSend() async{
    http.StreamedResponse streamedResponse;
    streamedResponse = await userAgentClient.send(streamedRequest);
    streamedResponse.stream.listen(
      (value) async{
          _body = http.ByteStream.fromBytes(value);
          _body = await _body.bytesToString();
      },
      onError: (e, sT) {
        SnackBar sBar = SnackBar(content: Text('$e\n$sT',));
        Scaffold.of(context).showSnackBar(sBar);
      },
      onDone: () {
        SnackBar sBar = SnackBar(content: Text('Done lol'),);
        Scaffold.of(context).showSnackBar(sBar);
      },
    );
    setState(() {
      _body;
      _status = streamedResponse.statusCode;
      _headers = streamedResponse.headers;
      _reason = streamedResponse.reasonPhrase;
    });
  }
}

void _httpClose(){
  if (streamedRequest != null){
    streamedRequest.sink.close();
  }
}

因此,我运行前两个函数,但是直到运行_httpClose()函数,屏幕上才会显示_body变量.

So I run the first 2 functions but the _body variable doesn't show up on my screen until I run the _httpClose() function.

推荐答案

Map<String,String>无法流式传输. 流式传输是指流每次发送大块数据并且服务器(或浏览器发送缓冲区)准备好接收更多数据时,以大块形式发送数据. 可以分块List<int>,因为一次发送多少字节无关紧要. 如果所有数据都随时可用,那么您可能不希望使用StreamedRequest,特别是如果它不是数据块时. https://en.wikipedia.org/wiki/Binary_large_object

Map<String,String> can not be streamed. Streamed means the data is sent in chunks every time a chunk of data is emitted by the stream and the server (or the browsers send buffer) is ready to receive more data. List<int> can be chunked because it doesn't matter how many bytes are sent at once. If you have all data readily available, you probably do not want to use a StreamedRequest, expecially if it is not a blob of data. https://en.wikipedia.org/wiki/Binary_large_object

utf8.encode可用于对流发出的块进行编码,但它本身并不提供流,因此您无法将utf8.encode的结果添加到接收器中.

utf8.encode can be used to encode chunks emitted by a stream, but it doesn't provide a stream by itself, so you can't add the result of utf8.encode to a sink.

  1. 我不明白这个问题.您想访问哪些属性?尝试时遇到什么问题?

在我看来,您不需要在用例中使用StreamedRequest.

To me it doesn't look like you don't need to use StreamedRequest for your use case.

这篇关于Flutter http streamedResponse.stream和streamedResponse.sink的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆