import asyncio
import urllib.parse
import sys
import socket
import socks
socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, "127.0.0.1", 9050, True)
@asyncio.coroutine
def print_http_headers(url):
url = urllib.parse.urlsplit(url)
s = socks.socksocket()
if url.scheme == 'https':
s.connect((url.hostname, 443))
connect = asyncio.open_connection(server_hostname='', ssl=True, sock=s)
else:
s.connect((url.hostname, 80))
connect = asyncio.open_connection(sock=s)
reader, writer = yield from connect
query = ('GET {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'))
while True:
line = yield from reader.readline()
if not line:
break
line = line.decode('latin1').rstrip()
if line:
print('HTTP header> %s' % line)
# Ignore the body, close the socket
writer.close()
url = sys.argv[1]
loop = asyncio.get_event_loop()
task = asyncio.ensure_future(print_http_headers(url))
loop.run_until_complete(task)
loop.close()