简体   繁体   English

Flutter Dart http2 如何向请求添加正文

[英]Flutter Dart http2 how to add body to request

I just started learning flutter about 1 and half month ago.大约 1 个半月前,我刚刚开始学习颤振。 All the tutorials I found are in http1.1.我找到的所有教程都在 http1.1 中。 We would like to use http2 for less latency.我们想使用 http2 来减少延迟。 I'm trying to use http2 instead of http1.1 for a flutter application.我正在尝试对颤振应用程序使用 http2 而不是 http1.1。

import 'package:http/http.dart' as HTTP;

looks like this:看起来像这样: 在此处输入图片说明

How can I add a body to the http2?如何向 http2 添加正文?

    var uri = Uri.parse('https://www.google.com/');

    var transport = new ClientTransportConnection.viaSocket(
      await SecureSocket.connect(
        uri.host,
        uri.port,
        supportedProtocols: ['h2'],
      ),
    );

    var stream = transport.makeRequest(
      [
        new Header.ascii(':method', method ?? 'GET'),
        // new Header.ascii(':method', 'GET'),
        new Header.ascii(':path', uri.path),
        new Header.ascii(':scheme', uri.scheme),
        new Header.ascii(':authority', uri.host),
      ],
      endStream: true,
    );
    Map<String, dynamic> res;
    await for (var message in stream.incomingMessages) {
      if (message is HeadersStreamMessage) {
        for (var header in message.headers) {
          var name = utf8.decode(header.name);
          var value = utf8.decode(header.value);
          res[name] = value;
          print('Header: $name: $value');
        }
      } else if (message is DataStreamMessage) {
        // Use [message.bytes] (but respect 'content-encoding' header)
      }
    }
    await transport.finish();
    return res;```
Thanks a lot! I couldn't find any examples with a body for http2 package. 

Use the sendData method.使用sendData方法。

You also need to convert the data to be sent into bytes.您还需要将要发送的数据转换为字节。

...


final bytes = utf8.encode(json.encode(body)); // body is a Map.

final headers = <Header>[
  Header.ascii(':method', 'POST'),
  Header.ascii(':path', uri.path),
  Header.ascii(':scheme', uri.scheme),
  Header.ascii(':authority', uri.host),
  Header.ascii('content-type', ContentType.json.toString()),
  Header.ascii('content-length', bytes.length.toString()),
];

var stream = transport.makeRequest(headers, endStream: false);
stream.sendData(bytes, endStream: true);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM