Skip to content

READING RESPONSE DATA - Different methods

Python
#!/usr/bin/env python3
"""READING RESPONSE DATA - Different methods"""
import urllib.request
url = "http://httpbin.org/get"
print("Reading Response Data:")
try:
    with urllib.request.urlopen(url) as response:
        # Method 1: read() all at once
        data = response.read()
        print(f"  read(): {len(data)} bytes")

    with urllib.request.urlopen(url) as response:
        # Method 2: read in chunks
        chunk_size = 100
        chunk = response.read(chunk_size)
        print(f"  read(100): {len(chunk)} bytes")

    with urllib.request.urlopen(url) as response:
        # Method 3: readline()
        line = response.readline()
        print(f"  readline(): {len(line)} bytes")
except Exception as e:
    print(f"  Error: {e}")