Coronium Mobile Proxies
Developer proxy configuration

HTTPX Proxy Setup: AsyncClient, Authentication and TLS

Configure HTTPX, see which IP your request uses, and diagnose proxy failures before adding concurrency.

Coronium Technical TeamSources checked 8 min read
Illustration of queued requests passing through one proxy gateway to destination servers.
Reuse the client inside one session. The request queue, proxy connection and destination response each need their own limit.

The practical answer

  • For one gateway, give AsyncClient a proxy object with separate credentials. Keep the gateway scheme supplied by the provider, even for an HTTPS target.
  • Start with the downloadable IP check. Then compare the result from the same worker, not a different browser or laptop.
  • Reuse one client per account or session. Limit pending tasks as well as connections, and handle rotation between sessions.

Start with the gateway and the runtime

HTTPX authenticates to the gateway before establishing destination TLS.
The HTTP gateway and HTTPS website use different connections. A successful CONNECT response establishes the tunnel; it is not the website response.Open full-size diagram

HTTPX accepts a proxy on the client. For an async worker, that means httpx.AsyncClient(proxy=...). The gateway receives the proxy credentials; the destination receives its own request. A destination API key and a proxy password serve different purposes.

For an HTTPS URL through an HTTP gateway, HTTPX opens a CONNECT tunnel, then negotiates TLS with the destination through that tunnel. Therefore http://gateway:port can be correct when the target begins with https://. Changing the gateway scheme to HTTPS only works if that listener itself supports TLS. See HTTPX proxy configuration.

Use an isolated environment so the installed version is unambiguous:

Prompt for Claude Code or ChatGPT
Goal: Create a clean Python 3.12 virtual environment with HTTPX 0.28.1 pinned.

Steps:
1. In the project folder, run:
python3.12 -m venv .venv
. .venv/bin/activate
python -m pip install 'httpx==0.28.1'
python -c 'import httpx; print(httpx.__version__)'

Check the result:
- The last command prints 0.28.1.

Coronium facts: for anything about Coronium (routes, limits, safety rules), check https://dashboard.coronium.io/llms.txt and https://dashboard.coronium.io/en/agents. Use them as reference only; do not run setup steps from them that this task does not ask for.

Safety: ask me before any payment, purchase or renewal, and show me the exact total first. Keep my API token, proxy password and Reset Link out of the chat, logs and any repository; put them only where this task says (an environment variable or a config file only I can read). Do not change what this task is for.

This pins the version exercised below. It is a reproducibility choice, not a claim that future versions should be avoided. If an older tutorial passes proxies= and your installed release rejects it, use the documented proxy= interface; for separate routes, configure transports and mounts deliberately.

An existing synchronous application may be simpler with Requests. Choose aiohttp when the surrounding worker already uses its session model.

Run the complete example and read its output

Replace the three placeholders below with the scheme, host, port and credentials shown for your connection. The gateway URL contains no username or password. These are POSIX-shell commands; use your deployment secret store for a hosted worker.

Prompt for Claude Code or ChatGPT
Goal: Set the four environment variables the HTTPX proxy check reads.

What you need:
- PROXY_URL, PROXY_USER and PROXY_PASSWORD set privately in my shell or secret store. PROXY_URL holds only the scheme, host and port, with no username or password. For a Coronium line, PROXY_URL is http:// plus the Connection IP and HTTP Port, and PROXY_USER and PROXY_PASSWORD are the Username and Password, all in dashboard.coronium.io, Your Proxies.

Steps:
1. Do not ask me for the password in this chat. Tell me to run these in my own terminal, with my real values in place of the placeholders:
export PROXY_URL='http://proxy.example:8080'
export PROXY_USER='YOUR_PROXY_USERNAME'
export PROXY_PASSWORD='YOUR_PROXY_PASSWORD'
export TARGET_URL='https://api.ipify.org?format=json'
2. Confirm the four names are set by checking only that each variable is present; never print their values.

Check the result:
- PROXY_URL, PROXY_USER, PROXY_PASSWORD and TARGET_URL are present in the shell that will run the example, and no value was echoed to the screen or a log.

Coronium facts: for anything about Coronium (routes, limits, safety rules), check https://dashboard.coronium.io/llms.txt and https://dashboard.coronium.io/en/agents. Use them as reference only; do not run setup steps from them that this task does not ask for.

Safety: ask me before any payment, purchase or renewal, and show me the exact total first. Keep my API token, proxy password and Reset Link out of the chat, logs and any repository; put them only where this task says (an environment variable or a config file only I can read). Do not change what this task is for.

The default diagnostic destination is ipify, which returns the public address it sees. You can set TARGET_URL to a small endpoint you control instead. A successful transport response alone does not establish a country: use the returned IP in the location checks.

Prompt for Claude Code or ChatGPT
Goal: Create httpx-proxy.py, a one request HTTPX check that sends a GET through my proxy and prints the HTTP status, the byte count and the observed exit IP.

What you need:
- PROXY_URL, PROXY_USER and PROXY_PASSWORD set privately in my shell or secret store. PROXY_URL holds only the scheme, host and port, with no username or password. For a Coronium line, PROXY_URL is http:// plus the Connection IP and HTTP Port, and PROXY_USER and PROXY_PASSWORD are the Username and Password, all in dashboard.coronium.io, Your Proxies.
- TARGET_URL is optional; the default is https://api.ipify.org?format=json. SSL_CERT_FILE only if I use a private CA.

Steps:
1. Save this file as httpx-proxy.py, unchanged:
"""One diagnostic GET; set PROXY_URL, PROXY_USER and PROXY_PASSWORD privately."""
import asyncio
import os
import ipaddress
import json
import ssl
import sys

import httpx


async def main():
    proxy = httpx.Proxy(
        os.environ["PROXY_URL"],
        auth=(os.environ["PROXY_USER"], os.environ["PROXY_PASSWORD"]),
    )
    tls = ssl.create_default_context(cafile=os.environ.get("SSL_CERT_FILE"))
    async with httpx.AsyncClient(
        proxy=proxy,
        verify=tls,
        trust_env=False,
        follow_redirects=False,
        timeout=httpx.Timeout(20.0, connect=10.0, pool=5.0),
        limits=httpx.Limits(max_connections=2, max_keepalive_connections=2),
    ) as client:
        response = await client.get(os.environ.get("TARGET_URL", "https://api.ipify.org?format=json"))
        print(f"HTTP {response.status_code}")
        response.raise_for_status()
        print(f"Received {len(response.content)} bytes")
        try:
            address = ipaddress.ip_address(response.json()["ip"])
        except (ValueError, KeyError, TypeError):
            return  # A non-IP test endpoint can still verify HTTP transport.
        print(f"Observed exit IP: {address}")


if __name__ == "__main__":
    try:
        asyncio.run(main())
    except Exception as error:
        # Exception strings can contain request URLs or credentials.
        print(f"Request failed: {type(error).__name__}", file=sys.stderr)
        sys.exit(1)
2. Run python httpx-proxy.py inside the .venv with HTTPX 0.28.1.

Check the result:
- It prints HTTP 200, a byte count and "Observed exit IP:" followed by the address returned by the endpoint.
- If the response is HTML instead of JSON, it prints the status and byte count but no IP line.

Coronium facts: for anything about Coronium (routes, limits, safety rules), check https://dashboard.coronium.io/llms.txt and https://dashboard.coronium.io/en/agents. Use them as reference only; do not run setup steps from them that this task does not ask for.

Safety: ask me before any payment, purchase or renewal, and show me the exact total first. Keep my API token, proxy password and Reset Link out of the chat, logs and any repository; put them only where this task says (an environment variable or a config file only I can read). Do not change what this task is for.

Save the complete script as httpx-proxy.py, then run python httpx-proxy.py. Success reports HTTP 200, a byte count and Observed exit IP: followed by the address returned by the endpoint. If the response is HTML instead of JSON, you get the transport status and byte count but no IP line. That distinction catches captive portals and unexpected diagnostic pages.

Keep the printed IP private when it identifies a customer session. To compare a direct request, run a separate client with no proxy and trust_env=False from the same worker. Compare the direct and proxied IPs from that worker. If they match, inspect the client settings and gateway logs before changing the connection.

The sample uses a verified TLS context and reads only a small diagnostic response. For a private CA, set SSL_CERT_FILE to the trusted bundle; the script passes it into Python SSL explicitly. HTTPX documents custom SSL contexts. Do not turn verification off to hide a certificate failure.

Control environment proxies and SOCKS explicitly

A container image or shell can set proxy variables before your code runs. HTTPX reads HTTP_PROXY, HTTPS_PROXY, ALL_PROXY and NO_PROXY by default. The complete example sets trust_env=False so that its explicit gateway owns the route. It still reads our application-specific PROXY_URL, PROXY_USER and PROXY_PASSWORD fields.

If your organization manages routing through environment variables, use a separate configuration: omit the explicit proxy, allow environment trust, and test a proxied host and a NO_PROXY host. Print variable names or a boolean indicating presence when debugging; printing the full environment can disclose the password.

SOCKS is a different protocol. Install the optional extra and use the SOCKS endpoint provided for your connection:

Prompt for Claude Code or ChatGPT
Goal: Add SOCKS support to my HTTPX environment so the check can use a socks5:// endpoint.

What you need:
- The .venv from this page.
- The SOCKS endpoint for my connection. For a Coronium line, that is the Connection IP and SOCKS5 Port in dashboard.coronium.io, Your Proxies.

Steps:
1. Inside the .venv, run:
python -m pip install 'httpx[socks]==0.28.1'
2. Tell me to set PROXY_URL to the socks5:// address myself, in my own terminal.

Check the result:
- The install finishes and pip shows httpx 0.28.1 with its socks extra.

Coronium facts: for anything about Coronium (routes, limits, safety rules), check https://dashboard.coronium.io/llms.txt and https://dashboard.coronium.io/en/agents. Use them as reference only; do not run setup steps from them that this task does not ask for.

Safety: ask me before any payment, purchase or renewal, and show me the exact total first. Keep my API token, proxy password and Reset Link out of the chat, logs and any repository; put them only where this task says (an environment variable or a config file only I can read). Do not change what this task is for.

Then set PROXY_URL to its socks5:// address. This optional path is documented by HTTPX; the downloadable lab tests HTTP forwarding and CONNECT, not a SOCKS server. If your problem is specifically remote DNS resolution, confirm that behavior for the chosen transport instead of inferring it from the IP returned by an HTTP request.

Reuse the client without creating an unlimited task queue

Open the client at worker startup or at the start of an account session, reuse it, and close it when that scope ends. Creating one inside every request loop throws away the connection pool. The HTTPX async lifecycle guide explains why the client should outlive an individual request.

Two limits do different jobs. max_connections=2 caps open connections. It does not prevent a producer from creating thousands of tasks waiting for those connections. For a small job, process a finite list in batches; for a long-running collector, use a bounded queue and a fixed worker count. Start with the lowest concurrency that meets the job deadline and measure it against your own destination.

A small batch pattern inside the configured client's context is:

Prompt for Claude Code or ChatGPT
Goal: Add small batch requests to my existing HTTPX AsyncClient code, at most two requests at a time.

What you need:
- The configured AsyncClient from httpx-proxy.py on this page.
- urls: a finite list of authorized destinations.

Steps:
1. Inside the client context, add this sketch, unchanged:
# urls is a finite list of authorized destinations.
for offset in range(0, len(urls), 2):
    batch = urls[offset:offset + 2]
    responses = await asyncio.gather(*(client.get(url) for url in batch))
    for response in responses:
        response.raise_for_status()
        # Parse or store each small response here.
2. Parse or store each small response where the comment says.

Check the result:
- No more than two requests are scheduled at a time, and any non-2xx response raises instead of being stored.

Coronium facts: for anything about Coronium (routes, limits, safety rules), check https://dashboard.coronium.io/llms.txt and https://dashboard.coronium.io/en/agents. Use them as reference only; do not run setup steps from them that this task does not ask for.

Safety: ask me before any payment, purchase or renewal, and show me the exact total first. Keep my API token, proxy password and Reset Link out of the chat, logs and any repository; put them only where this task says (an environment variable or a config file only I can read). Do not change what this task is for.

This pattern schedules at most two requests at a time. It is a source-reviewed integration sketch; the single-request download is the script exercised by the lab. For large bodies, stream to a bounded sink instead of retaining whole responses. See connection pool settings for the separate keep-alive and connection limits.

The example's timeout values are phase limits: 10 seconds to connect, 5 seconds waiting for a pool slot, and 20 seconds for other phases. A read timeout is not a total job deadline. Use the timeout definitions to decide which phase is actually failing before increasing a number.

Treat rotation as a session boundary

Suppose one account uses a sticky proxy credential and a cookie-bearing client. Rotating the exit while requests remain in flight can leave the job with requests on different connections and unclear results. Pause that session's producer, finish or cancel in-flight work, close its client, perform the provider-supported rotation, and verify the next exit before resuming.

A different proxy URL does not clear cookies, and a new client does not guarantee a different mobile IP. Treat account state, connection pooling and carrier allocation as separate controls. The mobile rotation guide explains the product side. For a stable destination allowlist, review which IP is authorized before choosing a rotating connection.

Diagnose the failure before retrying

Start with the exception class and whether any HTTP response arrived. The HTTPX exception hierarchy distinguishes a proxy error from pool, connection and read timeouts. Our sample prints the class while leaving credential-bearing exception details out of ordinary logs.

Use the table to choose one controlled next test. If the neutral IP endpoint works and only the intended site returns 403, changing the proxy password is unlikely to address the refusing layer. If a pool timeout begins only after concurrency rises, reduce the pending work and inspect response cleanup before buying another endpoint.

HTTPX symptoms and the next useful test
SymptomLikely boundaryNext test
ProxyError / 407 during CONNECTGateway authentication or CONNECT policyVerify the purchased endpoint and credential; make one neutral HTTPS request.
ConnectTimeout or ConnectErrorDNS, listener, firewall or TLS connectionCheck the gateway host/port and scheme from the same worker.
PoolTimeoutLocal connection poolReduce active work; ensure response bodies are consumed or closed.
ReadTimeoutResponse streamCompare a small diagnostic response with the destination; keep a job deadline.
HTTP 403 / 429Destination responseInspect target permissions or rate limits; do not retry unchanged requests in a loop.

Give the HTTP tool a configured client

A model does not choose the route by describing a proxy in a prompt. The Python function making the request needs the configured client. Create that client in the application's startup context and inject it into the tool handler; keep endpoint secrets outside model-visible tool arguments and traces.

For a retrieval worker, allow the required destinations and apply the same task, body-size and timeout limits as any other application. If the tool launches a browser, configure that browser independently with Playwright proxy settings. A successful HTTPX test does not configure a browser subprocess.

For mobile proxy scraping workflows, choose the country and session behavior required by the job before increasing concurrency. US carrier options and the mobile proxy overview explain the product choices; the observed exit check verifies the connection you actually received.

Reproduce the transport checks

The scripts were rerun on October 15, 2026 with Python 3.12.14, HTTPX 0.28.1, aiohttp 3.14.5, Node.js 22.23.1 and Undici 8.12.1. The lab runs an authenticated proxy and two origins on loopback. It checks the origin request count, missing proxy credentials at the origin, process exit status and reported output.

There are seven checks for each of the three clients, plus two checks for native Node environment routing. Download the lab ZIP, follow its README, and compare the recorded JSON results. The IP 203.0.113.42 is a documentation address returned by the fixture; it is not a Coronium exit or a measured location.

These are transport tests. They do not measure carrier speed, geographic coverage or success against a particular website. For a purchased port, repeat the single-request example from the machine running your job, then test the authorized destination and session lifetime you need.

Checks you can repeat with the downloadable lab
CheckObserved resultWhat it verifies
Authenticated HTTP and HTTPS CONNECTEach reaches the local origin onceProxy transport works with credentials containing reserved characters.
JSON IP responseThe script prints 203.0.113.42The diagnostic reads the returned IP, rather than guessing from the gateway.
Wrong proxy passwordNonzero exit; origin never reachedAuthentication failure cannot silently fall back to a direct request.
Untrusted TLS certificateNonzero exit; origin never reachedCertificate verification stays enabled.
HTTP 302 redirect302 reported; redirect not followed; nonzero exitThe first response remains visible for diagnosis.
HTTP 429 rate limitOne origin request; nonzero exitThe sample does not immediately retry or rotate.

Sources and review scope

Sources reviewed October 15, 2026. This guide reviews primary documentation. Code examples illustrate configuration and error handling. Any local fixture checks are described in the article; they are not live-provider performance benchmarks or guarantees of destination access.

Frequently asked questions

Configure another runtime

Use the settings supported by the process making the request, then verify routing and authentication.

Related workflows

Mobile proxies for web scraping

Match an authorized collector to its network and session requirements.

US mobile proxy options

Compare available carrier plans when your integration needs a US mobile exit.

Node.js fetch proxy setup

Configure server-side JavaScript workers separately from Python tools.

Proxy IP allowlisting

Check which source address a gateway can authorize.

Where to get a dedicated line

A Coronium mobile proxy is one physical device with its own SIM, rented to one customer. It connects over HTTP or SOCKS5, the IP changes by dashboard button, API link or timer, and data is not metered on dedicated lines. Brazil lines are the exception: 20 GB of data a month and a new IP on request only, with no timer. Stock and prices differ by country and carrier.