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

Java Proxy Setup

Set up HTTP proxies in Java with HttpClient, OkHttp, and Apache HttpClient. Enterprise-grade proxy configuration with Hex Proxies.

Requirements

  • Java 11+ (JDK)
  • Maven or Gradle
  • HttpClient or OkHttp

Installation

// Add to pom.xml or build.gradle

Code Example

import java.net.*;
import java.net.http.*;

// Java 11+ HttpClient with proxy
Authenticator auth = new Authenticator() {
    @Override
    protected PasswordAuthentication getPasswordAuthentication() {
        return new PasswordAuthentication(
            "user", "pass".toCharArray());
    }
};

HttpClient client = HttpClient.newBuilder()
    .proxy(ProxySelector.of(
        new InetSocketAddress("gate.hexproxies.com", 8080)))
    .authenticator(auth)
    .connectTimeout(Duration.ofSeconds(30))
    .build();

HttpRequest request = HttpRequest.newBuilder()
    .uri(URI.create("https://httpbin.org/ip"))
    .build();

HttpResponse<String> response = client.send(
    request, HttpResponse.BodyHandlers.ofString());
System.out.println(response.body());

Setup Steps

1

Choose your HTTP client

Use java.net.http.HttpClient for Java 11+, or add OkHttp/Apache HttpClient via Maven/Gradle for older versions.

2

Create the Authenticator

Subclass java.net.Authenticator and return your Hex Proxies credentials from getPasswordAuthentication().

3

Build the proxied client

Pass ProxySelector.of(new InetSocketAddress("gate.hexproxies.com", 8080)) and your authenticator to the builder.

4

Send a test request

Request httpbin.org/ip and verify the response body contains a Hex Proxies IP address.

5

Handle exceptions

Catch ConnectException, SocketTimeoutException, and SSLHandshakeException individually with appropriate recovery.

6

Externalize credentials

Read proxy user/pass from environment variables or a secrets manager, never from hardcoded strings.

Configuration Options

OptionDescription
Proxy SelectorProxySelector.of(new InetSocketAddress("gate.hexproxies.com", 8080)) for routing.
AuthenticatorCustom Authenticator subclass returning PasswordAuthentication with your credentials.
Connect TimeoutconnectTimeout(Duration.ofSeconds(30)) on HttpClient builder.
HTTP VersionHTTP/2 by default with HTTP/1.1 fallback for proxy CONNECT tunnels.
Thread PoolPass custom Executor to control concurrency for async sendAsync() calls.

Best Practices

  • Create one HttpClient instance at startup and share across threads for connection pool reuse.
  • Read proxy credentials from environment variables or a secrets manager like HashiCorp Vault.
  • Set connectTimeout and request timeout explicitly; Java defaults vary by implementation.
  • Use sendAsync() with CompletableFuture for non-blocking proxy requests in web servers.
  • For OkHttp, configure ConnectionPool with maxIdleConnections=10 and keepAliveDuration=5 minutes.
  • Implement retry with exponential backoff using a utility method rather than manual loops.
  • Log proxy response status and latency with SLF4J for production monitoring.
  • Use JVM system properties for quick proxy setup in legacy applications without code changes.

Java Proxy Setup

Java offers three distinct approaches to proxy configuration, each suited to different enterprise contexts. The java.net.http.HttpClient (Java 11+) provides a modern, immutable builder API with built-in async support. OkHttp adds connection pooling with configurable eviction and interceptor chains. Apache HttpClient 5 excels in legacy enterprise environments where fine-grained connection management and cookie policies are required.

Unlike dynamic languages, Java's proxy authentication uses a separate Authenticator class rather than embedding credentials in the URL. This design separates credential management from connection logic, which is better for enterprise security but requires more setup code.

Prerequisites

Before you begin, make sure you have: - An active Hex Proxies account with proxy credentials - Java 11+ (JDK) - Maven or Gradle - HttpClient or OkHttp

Basic Proxy Configuration

Java 11's HttpClient uses ProxySelector to route connections and a separate Authenticator for credentials. The client is immutable and thread-safe after construction.

import java.net.*;

Authenticator auth = new Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication( "user", "pass".toCharArray()); } };

HttpClient client = HttpClient.newBuilder() .proxy(ProxySelector.of( new InetSocketAddress("gate.hexproxies.com", 8080))) .authenticator(auth) .connectTimeout(Duration.ofSeconds(30)) .build();

HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://httpbin.org/ip")) .build();

HttpResponse<String> response = client.send( request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.body()); ```

Thread Safety and Connection Pooling

Java's HttpClient is thread-safe and maintains an internal connection pool. Create one client instance at application startup and share it across threads. OkHttp's ConnectionPool class allows configuring max idle connections and keep-alive duration for fine-tuned resource management.

JVM System Properties

For applications where you cannot modify the HTTP client code, set JVM-level proxy properties: -Dhttp.proxyHost=gate.hexproxies.com -Dhttp.proxyPort=8080. This routes all HTTP traffic through the proxy without code changes, useful for legacy applications and third-party libraries.

Configuration Options

  • **Proxy Host/Port** -- gate.hexproxies.com port 8080 via InetSocketAddress or system properties.
  • **Authenticator** -- Subclass java.net.Authenticator and override getPasswordAuthentication().
  • **Connect Timeout** -- Set via connectTimeout(Duration.ofSeconds(30)) on the builder.
  • **HTTP Version** -- HttpClient supports HTTP/2 by default, falling back to HTTP/1.1 for proxied requests.
  • **Executor** -- Pass a custom Executor for async requests to control thread pool sizing.

Error Handling

Java proxy errors manifest as checked exceptions that the compiler forces you to handle.

  1. java.net.ConnectException: Connection refused
  2. - The proxy gateway is unreachable from your JVM host
  3. - Verify DNS resolution of gate.hexproxies.com
  4. - Check firewall rules for outbound TCP on port 8080

2. java.net.SocketTimeoutException - Connection or read timed out through the proxy - Increase connectTimeout and request timeout values - Implement retry logic with a backoff multiplier

3. java.io.IOException: HTTP/1.1 407 Proxy Authentication Required - Authenticator is not set or returns wrong credentials - Verify Authenticator is passed to HttpClient.newBuilder() - Check that getPasswordAuthentication returns correct user/pass

4. javax.net.ssl.SSLHandshakeException - TLS certificate validation failed during CONNECT tunnel - Update the JVM's cacerts truststore with current CA certificates - Never disable certificate validation in production code

5. java.net.UnknownHostException - DNS resolution failed for the proxy hostname - Check network configuration and DNS server settings - Try using the proxy IP address directly as a diagnostic step ```

Wrap proxy calls in try-catch blocks and use specific exception types rather than catching generic Exception.

Error Handling

## Error Handling

Java proxy errors manifest as checked exceptions that the compiler forces you to handle.

1. java.net.ConnectException: Connection refused - The proxy gateway is unreachable from your JVM host - Verify DNS resolution of gate.hexproxies.com - Check firewall rules for outbound TCP on port 8080

2. java.net.SocketTimeoutException - Connection or read timed out through the proxy - Increase connectTimeout and request timeout values - Implement retry logic with a backoff multiplier

3. java.io.IOException: HTTP/1.1 407 Proxy Authentication Required - Authenticator is not set or returns wrong credentials - Verify Authenticator is passed to HttpClient.newBuilder() - Check that getPasswordAuthentication returns correct user/pass

4. javax.net.ssl.SSLHandshakeException - TLS certificate validation failed during CONNECT tunnel - Update the JVM's cacerts truststore with current CA certificates - Never disable certificate validation in production code

5. java.net.UnknownHostException - DNS resolution failed for the proxy hostname - Check network configuration and DNS server settings - Try using the proxy IP address directly as a diagnostic step ```

Wrap proxy calls in try-catch blocks and use specific exception types rather than catching generic Exception.

Frequently Asked Questions

How do I set a proxy in Java HttpClient?

Use HttpClient.newBuilder().proxy(ProxySelector.of(new InetSocketAddress("gate.hexproxies.com", 8080))) with an Authenticator for credentials.

Can I set proxies via JVM system properties?

Yes. Set -Dhttp.proxyHost=gate.hexproxies.com -Dhttp.proxyPort=8080 -Dhttp.proxyUser=user -Dhttp.proxyPassword=pass when launching the JVM.

Is HttpClient thread-safe?

Yes. Create one HttpClient instance and share it across threads. The internal connection pool handles concurrent requests safely.

How do I rotate IPs in Java?

Create a new HttpClient instance for each request, or use Hex Proxies session parameters in the proxy URL to control rotation behavior.

Ready to Get Started?

Set up Java with Hex Proxies in minutes.