An OkHttp proxy is configured on OkHttpClient.Builder, not on an individual Request. Use .proxy(proxy) for one explicit route or leave it unset to let proxySelector choose routes.
Authenticated proxies need proxyAuthenticator, which answers a 407 challenge with Proxy-Authorization. Stop when that header is already present so bad credentials cannot create an authentication loop.
Reuse OkHttpClient instances instead of creating one per request. A small pool of prebuilt clients provides predictable endpoint rotation without discarding connection pools and thread pools.
HTTPS still travels through an HTTP proxy by using CONNECT. Keep TLS verification enabled because the proxy changes the route, not the destination certificate requirements.
Prove the route before scaling. Compare the observed exit IP, validate the response, and classify proxy connection errors separately from destination HTTP errors.
What Is an OkHttp Proxy?
An OkHttp proxy is an intermediary server selected by an OkHttpClient for outbound HTTP and HTTPS connections. The application sends traffic to the proxy, which forwards it to the destination and returns the response. OkHttp still handles requests, responses, pooling, timeouts, and TLS; the proxy controls the network route and the source IP visible to the destination.
OkHttp uses Java's java.net.Proxy model. The current official OkHttp proxy API says an explicit takes precedence over . If no explicit proxy is set, the selector may choose one from system or application policy. Passing forces a direct connection instead.
This standard configuration works with an internal gateway, a debugging proxy, or a managed endpoint such as Nstproxy Residential Prime Proxies. A proxy changes routing; it does not grant permission to access a resource or replace destination-specific rate limits and terms.
Why Use a Proxy with OkHttp?
A proxy with OkHttp is useful when a Java or Android application needs controlled egress, localized QA, ad verification, public-data collection, or separation between traffic classes. It can also make a network path reproducible: the code identifies the selected route while operations can change the endpoint outside a deployment.
The session model should follow the workflow. Several requests belonging to one login or checkout flow may need a stable route, while unrelated checks may use rotation. Nstproxy's IP rotation overview explains that network pattern; the application still needs bounded concurrency, response validation, and retry limits.
OkHttp is designed for client reuse. Reusing a client preserves its connection pool and executor resources. If workloads need different proxy policies, create a small number of long-lived clients—one per policy or endpoint—instead of building a new client for every call.
Prerequisites
The examples require Java 8 or newer, Gradle, OkHttp 5.5.0, an authorized destination, and a proxy host and port. The current OkHttp repository lists Java 8+ and Android 5.0+ as supported baselines, while Maven Central's OkHttp artifact page provides current release metadata.
Keep proxy values in environment-backed secret storage. The examples read PROXY_HOST, PROXY_PORT, PROXY_USER, PROXY_PASSWORD, and TARGET_URL. Avoid logging credentials or a complete authenticated endpoint.
Connect OkHttp Through Nstproxy
Create an authenticated proxy endpoint, then attach it to a reusable OkHttpClient.
There are three practical OkHttp proxy methods: attach one explicit proxy, answer an authenticated proxy challenge, or rotate across a pool of reusable clients. Each Java example below was compiled and executed with OkHttp 5.5.0 against a purpose-built local proxy. The tests confirmed absolute-form HTTP requests, a successful 407 authentication retry, and deterministic routing through two endpoints.
Method 1: Configure One Explicit Proxy
Use an explicit proxy when every request from one client should follow the same route. Create a Java Proxy, attach it to the builder, and bound both connection time and total call time.
The executed test returned HTTP 200 and showed GET http://example.test/ip HTTP/1.1 at the local proxy. For an HTTPS target, OkHttp first asks an HTTP proxy to create a tunnel with CONNECT and then performs TLS with the destination through that tunnel. Do not disable certificate verification to solve a routing or local CA problem.
Method 2: Add Proxy Username and Password Authentication
Use proxyAuthenticator when the endpoint requires Basic proxy authentication. The authenticator runs after the proxy returns 407 Proxy Authentication Required; it should add credentials once and stop if the same request already has the header.
The verification proxy deliberately returned 407 on the first request. OkHttp called the authenticator, retried once, and the proxy confirmed that the second request contained valid authorization. The loop guard matters: returning another request after credentials have already failed can repeat challenges until OkHttp's follow-up limit is reached.
Proxy credentials are different from destination credentials. Use proxyAuthenticator for the proxy's 407 challenge and authenticator for the origin server's 401 challenge. Never send Proxy-Authorization as an ordinary destination header.
Method 3: Rotate a Pool of Proxy Endpoints
Use prebuilt clients when the application must choose among several distinct endpoints. This example keeps one reusable client per endpoint and selects them in round-robin order. Provider-side rotation through one gateway is usually simpler; client-side rotation is useful when endpoint identity and health must remain visible to the application.
importjava.net.InetSocketAddress;importjava.net.Proxy;importjava.time.Duration;importjava.util.ArrayList;importjava.util.List;importjava.util.concurrent.atomic.AtomicInteger;importokhttp3.OkHttpClient;importokhttp3.Request;importokhttp3.Response;publicfinalclassRotatingProxy{privatefinalList<OkHttpClient> clients;privatefinalAtomicInteger next =newAtomicInteger();privateRotatingProxy(List<InetSocketAddress> endpoints){this.clients =newArrayList<>();for(InetSocketAddress endpoint : endpoints){Proxy proxy =newProxy(Proxy.Type.HTTP, endpoint); clients.add(newOkHttpClient.Builder().proxy(proxy).connectTimeout(Duration.ofSeconds(5)).callTimeout(Duration.ofSeconds(15)).build());}}privateOkHttpClientnextClient(){return clients.get(Math.floorMod(next.getAndIncrement(), clients.size()));}publicstaticvoidmain(String[] args)throwsException{String proxyHost =requireEnv("PROXY_HOST");String[] ports =requireEnv("PROXY_PORTS").split(",");String targetUrl =System.getenv().getOrDefault("TARGET_URL","https://httpbin.org/ip");List<InetSocketAddress> endpoints =newArrayList<>();for(String port : ports){ endpoints.add(newInetSocketAddress(proxyHost,Integer.parseInt(port.trim())));}if(endpoints.size()<2){thrownewIllegalArgumentException("At least two proxy ports are required");}RotatingProxy pool =newRotatingProxy(endpoints);Request request =newRequest.Builder().url(targetUrl).build();for(int i =0; i < endpoints.size(); i++){try(Response response = pool.nextClient().newCall(request).execute()){if(!response.isSuccessful()){thrownewIllegalStateException("Unexpected status: "+ response.code());}System.out.println(response.body().string());}}}privatestaticStringrequireEnv(String name){String value =System.getenv(name);if(value ==null|| value.isBlank()){thrownewIllegalArgumentException(name +" is required");}return value;}}
The live run reported proxy ports 18180 and 18182 in that order. In production, store a non-secret endpoint ID beside each client, record success and latency by ID, and temporarily quarantine endpoints that repeatedly fail. Do not print the endpoint URL if it embeds credentials.
Explicit Proxy vs ProxySelector
Use .proxy(proxy) for a fixed client policy and proxySelector for destination-aware routing. A selector can return different Java Proxy values for different URIs and receive connectFailed notifications. The JDK's java.net.Proxy documentation defines HTTP, SOCKS, and direct proxy representations.
Do not configure both and expect them to merge. OkHttp consults proxySelector only when the explicit proxy is null. If a service must bypass the proxy for internal hosts, either create a direct client or implement a selector whose select(URI) method returns Proxy.NO_PROXY for those hosts. This is clearer than relying on an unnoticed machine-wide setting.
ProxySelector can supply fallback routes, but it is not automatically a request-by-request rotation engine. Connection reuse and route recovery affect which route is used. Use a provider gateway for network-level rotation or a deliberate client pool when each application call must have an auditable endpoint choice.
How to Verify an OkHttp Proxy
Verify an OkHttp proxy by checking the route and the response together. Send one direct request and one proxied request to an authorized IP-reflection endpoint, then compare the reported source addresses. A successful status alone does not prove the proxy handled the call.
Validate the response status, content type, and required body fields. An intermediary or destination can return an HTML block page with HTTP 200. The HTTP request glossary is a useful reference for the request/response boundary.
Next, test failure modes. Use an invalid port to confirm the connect timeout, invalid credentials to confirm a bounded 407 result, and a slow authorized target to confirm the call timeout. OkHttp event listeners can record DNS, connect, TLS, and response timing without exposing secrets. For another language's view of the same route, the Guzzle proxy guide offers a useful cross-check.
Choosing an Nstproxy Route for OkHttp
Nstproxy Residential Prime Proxies fit OkHttp applications that need an authenticated residential route with session and location controls exposed by the current product workflow. Java only needs a standard host, port, username, and password; no vendor-specific SDK is required for the proxy connection itself. Review the current Residential Prime billing models and test the exact target before selecting a route for production.
Prefer one gateway when the provider handles rotation. It keeps the OkHttp configuration small and preserves client reuse.
Use sticky behavior for multi-request sessions. Keep related calls on one route for the required session window.
Use an application pool only when endpoint-level control is necessary. Add health tracking, bounded retries, and non-secret route identifiers before increasing concurrency.
An Android application can use the same OkHttp builder APIs, but shipping long-lived proxy credentials inside a mobile binary is risky. Prefer short-lived credentials or a server-side network layer when possible. See the Android proxy server review for platform-level alternatives.
Common OkHttp Proxy Errors and Fixes
OkHttp proxy errors are easiest to fix when the connection layer is separated from the destination response.
Symptom
Likely cause
Practical fix
407 Proxy Authentication Required
Missing or rejected proxy credentials
Confirm the username/password, use proxyAuthenticator, and stop after the header has already been tried.
Connect timeout or ConnectException
Wrong host/port, unreachable route, or network policy
Verify the endpoint and keep a short connectTimeout; do not retry indefinitely.
TLS handshake failure
Invalid trust configuration, interception, or hostname mismatch
Repair the CA or route; keep certificate and hostname verification enabled.
Proxy appears unused
Explicit Proxy.NO_PROXY, selector policy, or a different client handled the call
Log a non-secret client/route ID and compare direct versus proxied exit-IP results.
403 or 429
The destination rejected or limited the request
Reduce request rate, confirm authorization, and follow the destination's rules.
Repeated 407 attempts
Authenticator returns a new request after credentials already failed
Return null when Proxy-Authorization is already present.
Retry only transient failures and use backoff. For state-changing requests, add idempotency protection before retrying. A new proxy IP cannot turn an invalid request into a valid one.
Conclusion
The cleanest OkHttp proxy setup is an explicit Proxy for one stable route, proxyAuthenticator for a 407 challenge, or a small pool of reusable clients for auditable endpoint rotation. Keep credentials outside source, use bounded timeouts, preserve TLS verification, and confirm both the exit route and response semantics.
Start with one authorized destination and one endpoint. Record a successful baseline, then add rotation or selector logic only when the application can identify failing routes and make a deliberate fallback decision.
Experience Nstproxy — Start Your Free Trial Today
Create an authenticated endpoint, connect one reusable OkHttp client, and verify the observed route before scaling.
Create a java.net.Proxy with the proxy type and InetSocketAddress, then pass it to new OkHttpClient.Builder().proxy(proxy).build(). Reuse the resulting client for calls that share that route.
Q: How do I add a proxy username and password in OkHttp?
Configure proxyAuthenticator and return a follow-up request containing Proxy-Authorization, commonly built with Credentials.basic(user, password). Return null if that header is already present to prevent repeated failed attempts.
Q: Does OkHttp support HTTPS through an HTTP proxy?
Yes. OkHttp uses the HTTP CONNECT method to create a tunnel through the proxy, then performs TLS with the destination. The proxy route does not justify disabling certificate or hostname verification.
Q: Does an explicit OkHttp proxy override ProxySelector?
Yes. OkHttp's explicit proxy setting takes precedence; proxySelector is consulted only when the explicit proxy is null. Use Proxy.NO_PROXY when a client must always connect directly.
Q: Should I create a new OkHttpClient for every rotating request?
No. Build a bounded set of reusable clients—one per endpoint or routing policy—and select among them. This preserves connection pools and avoids repeatedly creating executor resources.
Ivy Lin
Aug. 20th 2026
110M+ real IPs with 99.9% access success
Blazing-fast average response ~0.5s for high-concurrency tasks
From only $0.1/GB
Get immediate access to premium residential, datacenter, IPv6 and ISP proxy pools.