CUSTOM HEADERS - Adding HTTP headers
Python
#!/usr/bin/env python3
"""CUSTOM HEADERS - Adding HTTP headers"""
import urllib.request
url = "http://httpbin.org/headers"
req = urllib.request.Request(url)
req.add_header('User-Agent', 'MyApp/1.0')
req.add_header('Accept', 'application/json')
req.add_header('X-Custom-Header', 'CustomValue')
print("Custom Headers:")
try:
with urllib.request.urlopen(req) as response:
print(f" Status: {response.status}")
data = response.read().decode('utf-8')
print(f" Response length: {len(data)} bytes")
except Exception as e:
print(f" Error: {e}")