This repository has been archived by the owner on Oct 22, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 46
/
display_headers.dart
67 lines (56 loc) · 1.94 KB
/
display_headers.dart
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
// Copyright (c) 2024, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'package:http2/transport.dart';
void main(List<String> args) async {
if (args.length != 1) {
print('Usage: dart display_headers.dart <HTTPS_URI>');
exit(1);
}
var uriArg = args[0];
if (!uriArg.startsWith('https://')) {
print('URI must start with https://');
exit(1);
}
var uri = Uri.parse(uriArg);
var socket = await connect(uri);
// The default client settings will disable server pushes. We
// therefore do not need to deal with [stream.peerPushes].
var transport = ClientTransportConnection.viaSocket(socket);
var headers = [
Header.ascii(':method', 'GET'),
Header.ascii(':path', uri.path),
Header.ascii(':scheme', uri.scheme),
Header.ascii(':authority', uri.host),
];
var stream = transport.makeRequest(headers, endStream: true);
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);
print('$name: $value');
}
} else if (message is DataStreamMessage) {
// Use [message.bytes] (but respect 'content-encoding' header)
}
}
await transport.finish();
}
Future<Socket> connect(Uri uri) async {
var useSSL = uri.scheme == 'https';
if (useSSL) {
var secureSocket = await SecureSocket.connect(uri.host, uri.port,
supportedProtocols: ['h2']);
if (secureSocket.selectedProtocol != 'h2') {
throw Exception('Failed to negogiate http/2 via alpn. Maybe server '
"doesn't support http/2.");
}
return secureSocket;
} else {
return await Socket.connect(uri.host, uri.port);
}
}