A comprehensive HTTP client library that supports many features left out of other HTTP libraries.
—
Core HTTP client functionality providing request/response handling, connection management, caching, and authentication. The Http class serves as the primary interface for all HTTP operations in httplib2.
The main HTTP client class that manages connections, handles caching, authentication, redirects, and compression. Supports both HTTP and HTTPS with extensive configuration options.
class Http:
def __init__(self, cache=None, timeout=None, proxy_info=None,
ca_certs=None, disable_ssl_certificate_validation=False,
tls_maximum_version=None, tls_minimum_version=None):
"""
Initialize HTTP client.
Args:
cache: Cache object or directory path for caching
timeout (float): Socket timeout in seconds
proxy_info: ProxyInfo object or function returning ProxyInfo
ca_certs (str): Path to CA certificates file
disable_ssl_certificate_validation (bool): Skip SSL cert validation
tls_maximum_version: Maximum TLS version
tls_minimum_version: Minimum TLS version
"""
def request(self, uri, method="GET", body=None, headers=None,
redirections=5, connection_type=None):
"""
Perform a single HTTP request.
Args:
uri (str): Absolute URI of the HTTP resource
method (str): HTTP method (GET, POST, PUT, DELETE, etc.)
body (str or bytes): Entity body to send with request
headers (dict): Extra headers to send with request
redirections (int): Maximum number of redirects to follow (default 5)
connection_type: Connection class to use
Returns:
tuple: (Response, content) where Response contains status/headers
and content is the response body as bytes
Raises:
HttpLib2Error: Base class for all httplib2 errors
RedirectLimit: Too many redirects
ServerNotFoundError: Server hostname not found
RelativeURIError: URI is relative when absolute required
"""
def add_credentials(self, name, password, domain=""):
"""
Add credentials for authentication.
Args:
name (str): Username
password (str): Password
domain (str): Authentication domain (optional)
"""
def add_certificate(self, key, cert, domain, password=None):
"""
Add client certificate for authentication.
Args:
key (str): Path to private key file
cert (str): Path to certificate file
domain (str): Domain for certificate usage
password (str): Private key password (optional)
"""
def clear_credentials(self):
"""Remove all stored authentication credentials."""
def close(self):
"""
Close persistent connections and clear sensitive data.
Not thread-safe, requires external synchronization.
"""import httplib2
h = httplib2.Http()
(resp, content) = h.request("http://example.org/")
print(f"Status: {resp.status}")
print(f"Content-Type: {resp['content-type']}")
print(f"Body: {content.decode('utf-8')}")import httplib2
h = httplib2.Http()
body = '{"key": "value"}'
headers = {
'content-type': 'application/json',
'user-agent': 'MyApp/1.0'
}
(resp, content) = h.request(
"https://api.example.com/data",
"POST",
body=body,
headers=headers
)import httplib2
h = httplib2.Http()
h.add_credentials('username', 'password', 'api.example.com')
(resp, content) = h.request("https://api.example.com/protected")import httplib2
# Use file-based cache in .cache directory
h = httplib2.Http(".cache")
# First request - fetches from server and caches
(resp, content) = h.request("http://example.org/")
# Second request - may use cached version if valid
(resp, content) = h.request("http://example.org/")
# Force fresh request ignoring cache
headers = {'cache-control': 'no-cache'}
(resp, content) = h.request("http://example.org/", headers=headers)import httplib2
h = httplib2.Http(
ca_certs="/path/to/cacerts.pem",
disable_ssl_certificate_validation=False,
tls_minimum_version="TLSv1_2"
)
(resp, content) = h.request("https://secure.example.com/")import httplib2
proxy_info = httplib2.ProxyInfo(
httplib2.socks.PROXY_TYPE_HTTP,
'proxy.example.com',
8080,
proxy_user='proxyuser',
proxy_pass='proxypass'
)
h = httplib2.Http(proxy_info=proxy_info)
(resp, content) = h.request("http://example.org/")httplib2 automatically manages HTTP connections:
All HTTP methods are supported:
Install with Tessl CLI
npx tessl i tessl/pypi-httplib2