POST REQUESTS - Sending data with urllib
Python
#!/usr/bin/env python3
"""
POST REQUESTS - Sending data with urllib
Demonstrates HTTP POST with form data
"""
import urllib.request
import urllib.parse
print("=" * 60)
print("POST REQUESTS - Sending Data")
print("=" * 60)
# Example 1: Basic POST request
print("\n1. Basic POST Request")
print("-" * 40)
url = "http://httpbin.org/post"
data = {'name': 'John', 'age': '30'}
encoded_data = urllib.parse.urlencode(data).encode('utf-8')
try:
request = urllib.request.Request(url, data=encoded_data)
with urllib.request.urlopen(request) as response:
print(f" Status: {response.status}")
print(f" Method: POST")
result = response.read().decode('utf-8')
print(f" Response length: {len(result)} bytes")
except Exception as e:
print(f" Error: {e}")
# Example 2: POST with multiple fields
print("\n2. POST with Multiple Fields")
print("-" * 40)
form_data = {
'username': 'alice',
'password': 'secret123',
'email': 'alice@example.com'
}
encoded = urllib.parse.urlencode(form_data).encode('utf-8')
try:
req = urllib.request.Request(url, data=encoded, method='POST')
with urllib.request.urlopen(req) as response:
print(f" Posted {len(form_data)} fields")
print(f" Status: {response.status}")
except Exception as e:
print(f" Error: {e}")
# Example 3: POST JSON data
print("\n3. POST JSON Data")
print("-" * 40)
import json
json_data = {'key': 'value', 'number': 42}
json_bytes = json.dumps(json_data).encode('utf-8')
try:
req = urllib.request.Request(url, data=json_bytes)
req.add_header('Content-Type', 'application/json')
with urllib.request.urlopen(req) as response:
print(f" Posted JSON data")
print(f" Status: {response.status}")
except Exception as e:
print(f" Error: {e}")
# Example 4: POST with explicit method
print("\n4. Explicit POST Method")
print("-" * 40)
data = urllib.parse.urlencode({'test': 'data'}).encode()
try:
req = urllib.request.Request(url, data=data, method='POST')
print(f" Method: {req.method}")
print(f" Has data: {req.data is not None}")
except Exception as e:
print(f" Error: {e}")
# Example 5: Form submission simulation
print("\n5. Simulate Form Submission")
print("-" * 40)
form_fields = {
'search': 'python urllib',
'category': 'documentation',
'sort': 'relevance'
}
encoded_form = urllib.parse.urlencode(form_fields).encode('utf-8')
try:
req = urllib.request.Request(url, data=encoded_form)
print(f" Form fields: {list(form_fields.keys())}")
print(f" Encoded length: {len(encoded_form)} bytes")
except Exception as e:
print(f" Error: {e}")
print("\n" + "=" * 60)
print("Key Points:")
print(" - POST requires data parameter")
print(" - Encode data with urlencode()")
print(" - Convert to bytes with encode()")
print(" - Set Content-Type for JSON")
print(" - Request object for custom methods")
print("=" * 60)