http.client

http client is very fast, but also low-level, and takes a few more lines of code than the others.


import http.client
import ssl
import sys

try:
conn = http.client.HTTPSConnection("www.hightail.com", port=443, timeout=5, context=ssl._create_unverified_context())
conn.request("GET", "/en_US/theme_default/images/hightop_250px.png")
resp = conn.getresponse()

if 301 <= resp.status <= 302:
print("Status: {}\nLocation: {}\n".format(resp.status,resp.headers['Location']))
else:
print("Status: {}\nContent-Type: {}\n".format(resp.status, resp.headers['Content-Type']))
body = resp.read()
if type(body) == str:
print("{}\n".format(body))
else:
sys.stdout.flush()
sys.stdout.buffer.write(body)
except Exception as e:
print("Status: 500\nContent-Type: text/plain\n\n{}".format(e))

Requests

Requests is a 3rd party, high level libary. It does have a simple format to use but is slower than the other two and may not be supported everywhere (not supported in AWS Lambda, for example)



import requests
import sys

url = "https://www.hightail.com/en_US/theme_default/images/hightop_250px.png"
try:
resp = requests.get(url, params = {}, timeout = 5, allow_redirects = False)
if 301 <= resp.status_code <= 302:
print("Status: {}\nLocation: {}\n".format(resp.status_code, resp.headers['Location']))
else:
print("Status: {}\nContent-Type: {}\n".format(resp.status_code, resp.headers['Content-Type']))
sys.stdout.flush()
sys.stdout.buffer.write(resp._content)
except Exception as e:
print("Status: 500\nContent-Type: text/plain\n\n{}".format(e))