Commit 1dc499c5 authored by Victor Stinner's avatar Victor Stinner

asyncio doc: the "Get HTTP headers" example now supports HTTPS

parent 5946922c
...@@ -238,8 +238,11 @@ IncompleteReadError ...@@ -238,8 +238,11 @@ IncompleteReadError
Read bytes string before the end of stream was reached (:class:`bytes`). Read bytes string before the end of stream was reached (:class:`bytes`).
Example Stream examples
======= ===============
Get HTTP headers
----------------
Simple example querying HTTP headers of the URL passed on the command line:: Simple example querying HTTP headers of the URL passed on the command line::
...@@ -250,10 +253,14 @@ Simple example querying HTTP headers of the URL passed on the command line:: ...@@ -250,10 +253,14 @@ Simple example querying HTTP headers of the URL passed on the command line::
@asyncio.coroutine @asyncio.coroutine
def print_http_headers(url): def print_http_headers(url):
url = urllib.parse.urlsplit(url) url = urllib.parse.urlsplit(url)
reader, writer = yield from asyncio.open_connection(url.hostname, 80) if url.scheme == 'https':
query = ('HEAD {url.path} HTTP/1.0\r\n' connect = asyncio.open_connection(url.hostname, 443, ssl=True)
'Host: {url.hostname}\r\n' else:
'\r\n').format(url=url) connect = asyncio.open_connection(url.hostname, 80)
reader, writer = yield from connect
query = ('HEAD {path} HTTP/1.0\r\n'
'Host: {hostname}\r\n'
'\r\n').format(path=url.path or '/', hostname=url.hostname)
writer.write(query.encode('latin-1')) writer.write(query.encode('latin-1'))
while True: while True:
line = yield from reader.readline() line = yield from reader.readline()
...@@ -263,6 +270,9 @@ Simple example querying HTTP headers of the URL passed on the command line:: ...@@ -263,6 +270,9 @@ Simple example querying HTTP headers of the URL passed on the command line::
if line: if line:
print('HTTP header> %s' % line) print('HTTP header> %s' % line)
# Ignore the body, close the socket
writer.close()
url = sys.argv[1] url = sys.argv[1]
loop = asyncio.get_event_loop() loop = asyncio.get_event_loop()
task = asyncio.async(print_http_headers(url)) task = asyncio.async(print_http_headers(url))
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment