4

I just started learning flutter about 1 and half month ago. All the tutorials I found are in http1.1. We would like to use http2 for less latency. I'm trying to use http2 instead of http1.1 for a flutter application.

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

looks like this: enter image description here

How can I add a body to the 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.

Abion47
  • 22,211
  • 4
  • 65
  • 88
nunuh89
  • 543
  • 1
  • 5
  • 11

1 Answers1

2

Use the sendData method.

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

kazumw
  • 21
  • 4