Python SSL Proxy Examples
Complete guide with working examples for configuring SSL proxy in Python using requests, urllib3, and aiohttp libraries
What is an SSL Proxy?
An SSL proxy is a proxy server that handles encrypted HTTPS connections. When you make HTTP requests through an SSL proxy, the proxy terminates the SSL connection, processes the request, and establishes a new SSL connection to the target server.
Use Case: SSL proxies are commonly used for security compliance, IP whitelisting, and maintaining consistent IP addresses for API access.
Python Requests with SSL Proxy
Basic SSL Proxy Configuration
import requests
# Your SSL proxy configuration
PROXY_HOST = "192.168.1.100" # Your static IP
PROXY_PORT = 8080
PROXY_USER = "your_proxy_username"
PROXY_PASS = "your_proxy_password"
# Configure HTTPS proxy (SSL proxy)
proxies = {
'https': f'https://{PROXY_USER}:{PROXY_PASS}@{PROXY_HOST}:{PROXY_PORT}'
}
# Make HTTPS request through SSL proxy
try:
response = requests.get(
'https://api.example.com/data',
proxies=proxies,
verify=True, # Enable SSL verification
timeout=30
)
print(f"Status Code: {response.status_code}")
print(f"Response: {response.text[:100]}...")
except requests.exceptions.ProxyError as e:
print(f"Proxy error: {e}")
except requests.exceptions.SSLError as e:
print(f"SSL error: {e}")
except Exception as e:
print(f"Request failed: {e}")
SSL Certificate Handling
import requests
import ssl
# Configure SSL context for custom certificate handling
ssl_context = ssl.create_default_context()
ssl_context.check_hostname = False
ssl_context.verify_mode = ssl.CERT_NONE
# For self-signed certificates or custom CA
proxies = {
'https': f'https://{PROXY_USER}:{PROXY_PASS}@{PROXY_HOST}:{PROXY_PORT}'
}
try:
response = requests.get(
'https://api.example.com/data',
proxies=proxies,
verify=ssl_context, # Use custom SSL context
timeout=30
)
print(f"Request successful: {response.status_code}")
except Exception as e:
print(f"Request failed: {e}")
Session with SSL Proxy
import requests
from requests.adapters import HTTPAdapter
from urllib3.util.retry import Retry
# Create session with SSL proxy
session = requests.Session()
# Configure retry strategy
retry_strategy = Retry(
total=3,
backoff_factor=1,
status_forcelist=[429, 500, 502, 503, 504],
)
adapter = HTTPAdapter(max_retries=retry_strategy)
session.mount("https://", adapter)
# Configure SSL proxy for the session
session.proxies = {
'https': f'https://{PROXY_USER}:{PROXY_PASS}@{PROXY_HOST}:{PROXY_PORT}'
}
# Make multiple requests through the same session
try:
# First request
response1 = session.get('https://api.example.com/endpoint1')
print(f"Request 1: {response1.status_code}")
# Second request (reuses proxy configuration)
response2 = session.get('https://api.example.com/endpoint2')
print(f"Request 2: {response2.status_code}")
except Exception as e:
print(f"Session request failed: {e}")
urllib3 with SSL Proxy
Basic SSL Proxy Configuration
import urllib3
import ssl
# Your SSL proxy configuration
PROXY_HOST = "192.168.1.100"
PROXY_PORT = 8080
PROXY_USER = "your_proxy_username"
PROXY_PASS = "your_proxy_password"
# Create proxy manager for SSL
proxy_url = f"https://{PROXY_USER}:{PROXY_PASS}@{PROXY_HOST}:{PROXY_PORT}"
proxy = urllib3.ProxyManager(proxy_url)
# Create HTTPS proxy pool
https_proxy_pool = urllib3.ProxyManager(
proxy_url=proxy_url,
num_pools=10,
maxsize=10,
retries=urllib3.Retry(total=3, backoff_factor=0.1),
ca_certs='/path/to/ca-bundle.crt' # Use system certificates
)
# Create HTTP client with SSL proxy
http = urllib3.PoolManager(
proxy_headers={'User-Agent': 'Mozilla/5.0'},
proxy=proxy,
ca_certs='/path/to/ca-bundle.crt'
)
# Make HTTPS request through SSL proxy
try:
response = http.request(
'GET',
'https://api.example.com/data'
)
print(f"Status Code: {response.status}")
print(f"Response: {response.data[:100].decode('utf-8')}...")
except urllib3.exceptions.ProxyError as e:
print(f"Proxy error: {e}")
except urllib3.exceptions.SSLError as e:
print(f"SSL error: {e}")
except Exception as e:
print(f"Request failed: {e}")
Custom SSL Context
import urllib3
import ssl
# Create custom SSL context
ssl_context = ssl.create_default_context()
ssl_context.check_hostname = False
ssl_context.verify_mode = ssl.CERT_NONE
# SSL proxy configuration
proxy_url = f"https://{PROXY_USER}:{PROXY_PASS}@{PROXY_HOST}:{PROXY_PORT}"
proxy = urllib3.ProxyManager(proxy_url)
# Create HTTP client with custom SSL context
http = urllib3.PoolManager(
proxy=proxy,
ssl_context=ssl_context,
cert_reqs='CERT_NONE',
assert_hostname=False
)
# Make HTTPS request with custom SSL handling
try:
response = http.request('GET', 'https://self-signed.badssl.com/')
print(f"Self-signed site accessed: {response.status}")
except Exception as e:
print(f"Request failed: {e}")
aiohttp (Async) with SSL Proxy
Async SSL Proxy Configuration
import aiohttp
import asyncio
import ssl
# Your SSL proxy configuration
PROXY_HOST = "192.168.1.100"
PROXY_PORT = 8080
PROXY_USER = "your_proxy_username"
PROXY_PASS = "your_proxy_password"
class SSLProxyClient:
def __init__(self):
self.proxy_url = f"https://{PROXY_USER}:{PROXY_PASS}@{PROXY_HOST}:{PROXY_PORT}"
self.ssl_context = ssl.create_default_context()
async def fetch_data(self, url):
"""Fetch data through SSL proxy"""
connector = aiohttp.TCPConnector()
# Create session with SSL proxy
async with aiohttp.ClientSession(
connector=connector,
trust_env=True
) as session:
try:
# Configure proxy for this session
session._default_headers.update({
'Proxy-Authorization': f'Basic {self._get_auth()}'
})
# Make HTTPS request through SSL proxy
async with session.get(
url,
proxy=self.proxy_url,
ssl=self.ssl_context
) as response:
print(f"Status: {response.status}")
data = await response.text()
print(f"Response length: {len(data)} characters")
return data
except aiohttp.ClientProxyConnectionError as e:
print(f"Proxy connection error: {e}")
return None
except aiohttp.ClientSSLError as e:
print(f"SSL error: {e}")
return None
except Exception as e:
print(f"Request failed: {e}")
return None
def _get_auth(self):
"""Get basic authentication header"""
import base64
auth_str = f"{PROXY_USER}:{PROXY_PASS}"
return base64.b64encode(auth_str.encode()).decode()
# Usage example
async def main():
client = SSLProxyClient()
# Fetch data through SSL proxy
result = await client.fetch_data('https://api.example.com/data')
if result:
print("Request successful!")
else:
print("Request failed!")
# Run the async function
if __name__ == "__main__":
asyncio.run(main())
Alternative: Using ProxyConnector
import aiohttp
import asyncio
from aiohttp_socks import ProxyConnector
# SSL proxy configuration
proxy_host = "192.168.1.100"
proxy_port = 8080
proxy_user = "your_proxy_username"
proxy_pass = "your_proxy_password"
async def fetch_with_proxy_connector():
"""Fetch using ProxyConnector"""
# Create proxy connector
connector = ProxyConnector.from_url(
f"https://{proxy_user}:{proxy_pass}@{proxy_host}:{proxy_port}"
)
async with aiohttp.ClientSession(connector=connector) as session:
try:
async with session.get('https://api.example.com/data') as response:
print(f"Status: {response.status}")
data = await response.text()
print(f"Response: {data[:100]}...")
return data
except Exception as e:
print(f"Request failed: {e}")
return None
# Run the function
if __name__ == "__main__":
asyncio.run(fetch_with_proxy_connector())
SSL Proxy Best Practices
1. Always Use HTTPS
Never send credentials or sensitive data over unencrypted connections when using proxies.
2. Verify SSL Certificates
Always verify SSL certificates unless you have a specific reason not to. Use system CA bundles when possible.
3. Use Session Objects
Reuse sessions for multiple requests to improve performance and maintain consistent proxy settings.
4. Handle Timeouts
Set appropriate timeouts to prevent hanging connections, especially when using proxies.
5. Monitor Performance
Monitor proxy performance and switch to faster proxies if needed.
Common Issues and Solutions
SSL Certificate Verification Errors
Solution: Use system CA certificates or disable verification only for specific trusted proxies.
Proxy Authentication Failures
Solution: Double-check proxy credentials and ensure the username:password format is correct.
Connection Timeouts
Solution: Increase timeout values or use connection pooling for better performance.
DNS Resolution Issues
Solution: Ensure proxy server can resolve target domain names or use IP addresses directly.
Ready to Use SSL Proxy in Python?
Get your static SSL proxy IPs today and start making secure HTTPS connections with consistent IP addresses for compliance and security requirements.
Get Started with OutboundGatewayRelated SSL Proxy Guides
Node.js SSL Proxy
JavaScript/Node.js implementation with axios, fetch, and undici libraries.
View Node.js Guide →PHP SSL Proxy
Web-focused proxy configuration with cURL, Guzzle, and Symfony HTTP Client.
View PHP Guide →📖 Language Comparison: Looking for the best approach? Python offers excellent libraries like requests and aiohttp, while Node.js provides native async support. Java is ideal for enterprise applications, PHP works well for web applications, and cURL is perfect for shell scripting.