@@ -238,8 +238,11 @@ IncompleteReadError
238238 Read bytes string before the end of stream was reached (:class: `bytes `).
239239
240240
241- Example
242- =======
241+ Stream examples
242+ ===============
243+
244+ Get HTTP headers
245+ ----------------
243246
244247Simple example querying HTTP headers of the URL passed on the command line::
245248
@@ -250,10 +253,14 @@ Simple example querying HTTP headers of the URL passed on the command line::
250253 @asyncio.coroutine
251254 def print_http_headers(url):
252255 url = urllib.parse.urlsplit(url)
253- reader, writer = yield from asyncio.open_connection(url.hostname, 80)
254- query = ('HEAD {url.path} HTTP/1.0\r\n'
255- 'Host: {url.hostname}\r\n'
256- '\r\n').format(url=url)
256+ if url.scheme == 'https':
257+ connect = asyncio.open_connection(url.hostname, 443, ssl=True)
258+ else:
259+ connect = asyncio.open_connection(url.hostname, 80)
260+ reader, writer = yield from connect
261+ query = ('HEAD {path} HTTP/1.0\r\n'
262+ 'Host: {hostname}\r\n'
263+ '\r\n').format(path=url.path or '/', hostname=url.hostname)
257264 writer.write(query.encode('latin-1'))
258265 while True:
259266 line = yield from reader.readline()
@@ -263,6 +270,9 @@ Simple example querying HTTP headers of the URL passed on the command line::
263270 if line:
264271 print('HTTP header> %s' % line)
265272
273+ # Ignore the body, close the socket
274+ writer.close()
275+
266276 url = sys.argv[1]
267277 loop = asyncio.get_event_loop()
268278 task = asyncio.async(print_http_headers(url))
0 commit comments