v1.10.82-f67ee7d
Skip to main content
← Back to Hex Proxies

OkHttp (Java) Proxy Integration

Configure OkHttp to route requests through Hex Proxies.

OkHttp Proxy Setup

OkHttp is the most widely used HTTP client in the Java and Android ecosystem. Its connection pooling, transparent compression, and interceptor architecture make it an excellent choice for proxy-based workflows. OkHttp handles proxy CONNECT tunneling automatically for HTTPS targets, and its authenticator callback cleanly separates proxy credentials from request logic.

Complete Configuration with Authentication

import okhttp3.*;
import java.net.InetSocketAddress;

Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("gate.hexproxies.com", 8080));

OkHttpClient client = new OkHttpClient.Builder() .proxy(proxy) .proxyAuthenticator((route, response) -> { String credential = Credentials.basic( System.getenv("PROXY_USER"), System.getenv("PROXY_PASS") ); return response.request().newBuilder() .header("Proxy-Authorization", credential) .build(); }) .connectTimeout(15, java.util.concurrent.TimeUnit.SECONDS) .readTimeout(30, java.util.concurrent.TimeUnit.SECONDS) .connectionPool(new ConnectionPool(20, 5, java.util.concurrent.TimeUnit.MINUTES)) .build();

Request request = new Request.Builder() .url("https://httpbin.org/ip") .header("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64)") .build();

try (Response response = client.newCall(request).execute()) { System.out.println(response.body().string()); } ```

Using Interceptors for Proxy Metrics

OkHttp's interceptor chain lets you log proxy performance without modifying request code. Add a network interceptor to track response times, status codes, and data transfer through the proxy:

client = client.newBuilder()
    .addNetworkInterceptor(chain -> {
        long start = System.nanoTime();
        Response response = chain.proceed(chain.request());
        long elapsed = (System.nanoTime() - start) / 1_000_000;
        System.out.printf("[%d] %s - %dms%n",
            response.code(), chain.request().url(), elapsed);
        return response;
    })
    .build();

Common Pitfalls

The most frequent mistake is creating a new OkHttpClient per request. OkHttp maintains a connection pool and thread pool internally — creating multiple clients wastes these resources and prevents connection reuse through the proxy. Always create one client and reuse it across all requests.

Another issue: the proxyAuthenticator callback fires on every 407 response. If your credentials are wrong, OkHttp will retry indefinitely. Add a retry counter in the authenticator to bail after 3 attempts and prevent infinite authentication loops.

Retry and Rotation Strategy

For residential proxy rotation, generate a unique session ID per request and embed it in the proxy username. Create a new proxy authenticator that appends the session ID:

String sessionUser = System.getenv("PROXY_USER") + "-session-" +
    UUID.randomUUID().toString().substring(0, 8);

Performance Tuning

Set the connection pool size to match your proxy plan's concurrency limit. OkHttp defaults to 5 idle connections — increase this for high-throughput proxy workloads. Set connect timeout to 15 seconds for residential proxies, which have higher handshake latency than direct connections.

Integration Steps

1

Create proxy and authenticator

Initialize a java.net.Proxy with the Hex Proxies gateway address and add a proxyAuthenticator that provides credentials from environment variables.

2

Configure timeouts and connection pool

Set connect timeout to 15s and read timeout to 30s for residential proxy latency. Size the connection pool to match your plan concurrency.

3

Reuse the client across all requests

Create one OkHttpClient instance and share it across your application. OkHttp handles connection pooling through the proxy automatically.

4

Add interceptors for monitoring

Use network interceptors to log proxy response times and detect blocks (403/429) for automatic retry logic.

Operational Tips

Keep sessions stable for workflows that depend on consistent identity. For high-volume collection, rotate IPs and reduce concurrency if you see timeouts or 403 responses.

  • Prefer sticky sessions for multi-step flows (auth, checkout, forms).
  • Rotate per request for scale and broad coverage.
  • Use timeouts and retries to handle transient failures.

Frequently Asked Questions

Can I use SOCKS5 with OkHttp?

Yes. Change Proxy.Type.HTTP to Proxy.Type.SOCKS and OkHttp will route through a SOCKS5 proxy. Note that SOCKS proxy authentication requires a custom SocketFactory.

How do I rotate IPs between OkHttp requests?

Append a unique session ID to your proxy username for each request. The Hex Proxies gateway assigns a different residential IP per session ID. Generate the session ID in a request interceptor for automatic per-request rotation.

Why does my OkHttp proxy authentication loop infinitely?

The proxyAuthenticator fires on every 407 response. If credentials are wrong, OkHttp retries forever. Add a counter in the authenticator callback and return null after 3 failed attempts to break the loop.

Ready to Integrate?

Start using residential proxies with OkHttp (Java) today.