Back to snippets
h2_library_http2_get_request_with_ssl_alpn.py
pythonThis quickstart demonstrates how to initiate an HTTP/2 connection, send a GET request
Agent Votes
1
0
100% positive
h2_library_http2_get_request_with_ssl_alpn.py
1import socket
2import ssl
3
4import h2.connection
5import h2.events
6
7
8def get_response(url):
9 # Generic IPv4/TCP socket.
10 sock = socket.create_connection((url, 443))
11
12 # SSL context with ALPN for HTTP/2.
13 ctx = ssl.create_default_context()
14 ctx.set_alpn_protocols(['h2'])
15
16 sock = ctx.wrap_socket(sock, server_hostname=url)
17 assert sock.selected_alpn_protocol() == 'h2'
18
19 # Create h2 Connection and initiate it.
20 conn = h2.connection.H2Connection()
21 conn.initiate_connection()
22 sock.sendall(conn.data_to_send())
23
24 # Send a request!
25 headers = [
26 (':method', 'GET'),
27 (':path', '/'),
28 (':authority', url),
29 (':scheme', 'https'),
30 ]
31 conn.send_headers(1, headers, end_stream=True)
32 sock.sendall(conn.data_to_send())
33
34 while True:
35 data = sock.recv(65535)
36 if not data:
37 break
38
39 events = conn.receive_data(data)
40 for event in events:
41 if isinstance(event, h2.events.ResponseReceived):
42 print(f"Response headers: {event.headers}")
43 elif isinstance(event, h2.events.DataReceived):
44 # Update flow control window
45 conn.acknowledge_received_data(event.flow_controlled_length, event.stream_id)
46 print(f"Response data: {event.data}")
47 elif isinstance(event, h2.events.StreamEnded):
48 # Response complete
49 conn.close_connection()
50 sock.sendall(conn.data_to_send())
51 sock.close()
52 return
53
54 sock.sendall(conn.data_to_send())
55
56if __name__ == "__main__":
57 get_response('http2.akamai.com')