v1.8.91-d84675c
← Back to Hex Proxies

Java OkHttp Proxy Setup

Last updated: April 2026

By Hex Proxies Engineering Team

Learn how to route HTTP requests through Hex Proxies using OkHttp in Java. Covers authentication, rotation, sticky sessions, and error handling.

intermediate15 minuteslanguage-integration

Prerequisites

  • Java 11 or later
  • OkHttp 4.x dependency
  • Hex Proxies account with credentials

Steps

1

Add OkHttp dependency

Add com.squareup.okhttp3:okhttp:4.x to your Maven or Gradle build file.

2

Create the proxy object

Instantiate java.net.Proxy with HTTP type pointing to gate.hexproxies.com:8080.

3

Set up authentication

Create a proxyAuthenticator that returns Proxy-Authorization credentials.

4

Build the client

Use OkHttpClient.Builder with proxy, authenticator, and timeout settings.

5

Send a test request

Make a request to httpbin.org/ip to verify your IP is proxied.

6

Add retry logic

Implement exponential backoff for 429 and 503 responses.

Java OkHttp Proxy Integration

OkHttp is one of the most popular HTTP clients in the Java ecosystem. It supports proxy configuration natively through `java.net.Proxy` and authenticators, making it straightforward to route traffic through Hex Proxies.

Basic Proxy Configuration

The simplest setup creates an OkHttp client that routes all requests through the Hex Proxies gateway:

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

public class ProxyClient { public static void main(String[] args) throws Exception { Proxy proxy = new Proxy( Proxy.Type.HTTP, new InetSocketAddress("gate.hexproxies.com", 8080) );

Authenticator proxyAuth = (route, response) -> { String credential = Credentials.basic("YOUR_USERNAME", "YOUR_PASSWORD"); return response.request().newBuilder() .header("Proxy-Authorization", credential) .build(); };

OkHttpClient client = new OkHttpClient.Builder() .proxy(proxy) .proxyAuthenticator(proxyAuth) .connectTimeout(15, java.util.concurrent.TimeUnit.SECONDS) .readTimeout(30, java.util.concurrent.TimeUnit.SECONDS) .build();

Request request = new Request.Builder() .url("https://httpbin.org/ip") .build();

try (Response response = client.newCall(request).execute()) { System.out.println("Status: " + response.code()); System.out.println("Body: " + response.body().string()); } } } ```

Sticky Sessions

For workflows that require the same IP across multiple requests -- such as logging in and then navigating authenticated pages -- append a session identifier to your username:

String stickyUser = "YOUR_USERNAME-session-abc123";
Authenticator stickyAuth = (route, response) -> {
    String credential = Credentials.basic(stickyUser, "YOUR_PASSWORD");
    return response.request().newBuilder()
        .header("Proxy-Authorization", credential)
        .build();

OkHttpClient stickyClient = new OkHttpClient.Builder() .proxy(proxy) .proxyAuthenticator(stickyAuth) .build(); ```

Rotation Strategy

For large-scale data collection, create a new client per batch or use a connection pool with short keep-alive times. Each new connection through `gate.hexproxies.com` automatically assigns a fresh IP from the 10M+ residential pool.

Error Handling with Retry

int maxRetries = 3;
for (int attempt = 1; attempt <= maxRetries; attempt++) {
    try (Response response = client.newCall(request).execute()) {
        if (response.isSuccessful()) {
            System.out.println(response.body().string());
            break;
        }
        if (response.code() == 429 || response.code() == 503) {
            Thread.sleep(attempt * 2000L);
            continue;
        }
        System.err.println("Failed with status: " + response.code());
        break;
    } catch (java.io.IOException e) {
        if (attempt == maxRetries) throw e;
        Thread.sleep(attempt * 2000L);
    }
}

SOCKS5 Support

OkHttp also supports SOCKS5 proxies for protocols beyond HTTP:

Proxy socks5 = new Proxy(
    Proxy.Type.SOCKS,
    new InetSocketAddress("gate.hexproxies.com", 1080)
);

Performance Considerations

  • Reuse OkHttpClient instances across requests to benefit from connection pooling.
  • Set explicit timeouts to avoid blocking threads on slow proxy responses.
  • Use the `ConnectionPool` class to control maximum idle connections and keep-alive duration.

Tips

  • *Reuse OkHttpClient instances -- creating a new client per request wastes resources.
  • *Use sticky sessions by appending a session ID to the username for multi-step flows.
  • *Set connectTimeout and readTimeout explicitly to avoid indefinite hangs.
  • *For SOCKS5, change the proxy type to Proxy.Type.SOCKS and use port 1080.

Ready to Get Started?

Put this guide into practice with Hex Proxies.

Cookie Preferences

We use cookies to ensure the best experience. You can customize your preferences below. Learn more