BASIC GET REQUEST - Using urllib.request
Python
#!/usr/bin/env python3
"""
BASIC GET REQUEST - Using urllib.request
Demonstrates simple HTTP GET requests
"""
import urllib.request
import urllib.error
print("=" * 60)
print("BASIC GET REQUEST - urllib.request.urlopen()")
print("=" * 60)
# Example 1: Simple GET request
print("\n1. Simple GET Request")
print("-" * 40)
url = "http://httpbin.org/get"
try:
response = urllib.request.urlopen(url)
print(f" URL: {url}")
print(f" Status: {response.status}")
print(f" Reason: {response.reason}")
data = response.read()
print(f" Response length: {len(data)} bytes")
except urllib.error.URLError as e:
print(f" Error: {e.reason}")
# Example 2: Read response as string
print("\n2. Read Response as String")
print("-" * 40)
try:
response = urllib.request.urlopen("http://httpbin.org/get")
html = response.read().decode('utf-8')
print(f" Response type: {type(html)}")
print(f" First 100 chars: {html[:100]}...")
except Exception as e:
print(f" Error: {e}")
# Example 3: Response info
print("\n3. Get Response Headers")
print("-" * 40)
try:
response = urllib.request.urlopen("http://httpbin.org/get")
print(f" Content-Type: {response.getheader('Content-Type')}")
print(f" Server: {response.getheader('Server')}")
print(f" Date: {response.getheader('Date')}")
except Exception as e:
print(f" Error: {e}")
# Example 4: Get URL info
print("\n4. Get URL Information")
print("-" * 40)
try:
response = urllib.request.urlopen("http://httpbin.org/get")
print(f" URL: {response.url}")
print(f" Status: {response.status}")
print(f" Headers type: {type(response.headers)}")
except Exception as e:
print(f" Error: {e}")
# Example 5: Context manager
print("\n5. Using Context Manager")
print("-" * 40)
try:
with urllib.request.urlopen("http://httpbin.org/get") as response:
print(f" Inside context: status = {response.status}")
data = response.read()
print(f" Data length: {len(data)}")
print(" Context closed automatically")
except Exception as e:
print(f" Error: {e}")
print("\n" + "=" * 60)
print("Key Points:")
print(" - urlopen() performs GET request by default")
print(" - Returns HTTPResponse object")
print(" - read() returns bytes, decode to string")
print(" - Use context manager for auto-cleanup")
print(" - Check status code for success")
print("=" * 60)