Skip to content

RESPONSE HEADERS - Reading HTTP headers

Python
#!/usr/bin/env python3
"""RESPONSE HEADERS - Reading HTTP headers"""
import urllib.request
print("Response Headers:")
url = "http://httpbin.org/response-headers?Custom-Header=Value"
try:
    with urllib.request.urlopen(url) as response:
        print(f"  All headers:")
        for header, value in response.headers.items():
            print(f"    {header}: {value[:50]}")
        print(f"\n  Specific headers:")
        print(f"    Content-Type: {response.getheader('Content-Type')}")
        print(f"    Server: {response.getheader('Server')}")
except Exception as e:
    print(f"  Error: {e}")