Proxy Grove
Skip to content

Using HTTP Proxies in Java Clients

Java proxy configuration for HttpClient, OkHttp and JVM system properties, with proxy authentication, timeouts and Proxy Grove HTTP and SOCKS5 endpoints.

Using HTTP Proxies in Java Clients

TL;DR: To use an HTTP proxy in Java, configure it on the client itself: pass a ProxySelector to java.net.http.HttpClient (Java 11 and later), or set a Proxy on OkHttp or Apache HttpClient. Use the JVM properties http.proxyHost and https.proxyHost only for quick scripts, because they affect every outbound call in the process. For proxy credentials, answer the 407 challenge with an Authenticator and remember that the JDK disables Basic authentication for HTTPS tunnels by default. Plug in the endpoint from your Residential Proxy or Mobile Proxy plan, and check plan details on pricing.

This guide shows working patterns for the standard library and the two most common third-party clients, explains the traps (global state, tunnel authentication, timeouts), and gives a short test routine. Replace the placeholder host, port and credentials with the values from your dashboard. See also the HTTP/HTTPS proxy product page.

Option 1: per-client proxy with java.net.http.HttpClient

The built-in client takes a ProxySelector in its builder. This keeps the proxy scoped to one client, so a metrics call or an internal service call elsewhere in the same application is not accidentally routed through it.

HttpClient client = HttpClient.newBuilder()
    .proxy(ProxySelector.of(new InetSocketAddress("PROXY_HOST", 8080)))
    .connectTimeout(Duration.ofSeconds(10))
    .build();

HttpRequest request = HttpRequest.newBuilder(URI.create("https://example.com/"))
    .timeout(Duration.ofSeconds(30))
    .GET()
    .build();

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

Always set both a connect timeout and a per-request timeout. Without them, a stalled proxy connection can hold a worker thread for a long time.

Option 2: proxy authentication

Most business proxy plans require a username and password. With HttpClient, supply an Authenticator that answers only proxy challenges:

Authenticator auth = new Authenticator() {
    @Override
    protected PasswordAuthentication getPasswordAuthentication() {
        if (getRequestorType() == RequestorType.PROXY) {
            return new PasswordAuthentication("PROXY_USER", "PROXY_PASS".toCharArray());
        }
        return null;
    }
};
HttpClient client = HttpClient.newBuilder()
    .proxy(ProxySelector.of(new InetSocketAddress("PROXY_HOST", 8080)))
    .authenticator(auth)
    .build();

The HTTPS tunnel gotcha

For HTTPS targets the client opens a tunnel with a CONNECT request. Since newer JDK updates, Basic authentication for that tunnel is disabled by default, so a correct username and password can still end in a 407 or a tunnel failure. The usual fix is to clear the disabled scheme list at startup, for example with -Djdk.http.auth.tunneling.disabledSchemes="". Apply this deliberately, and only in the process that needs it. Alternatively, authorize your server's egress IP with the provider if allowlisting fits your setup; credentials vs allowlisting compares the two.

Option 3: JVM system properties

For a one-off script, the properties are fast:

-Dhttp.proxyHost=PROXY_HOST -Dhttp.proxyPort=8080
-Dhttps.proxyHost=PROXY_HOST -Dhttps.proxyPort=8080
-Dhttp.nonProxyHosts="localhost|127.*|*.internal.example"

The drawback is scope. These settings are global, so every library that honors them will send traffic through the proxy, including health checks and calls to your own infrastructure. In production services, prefer the per-client approach and keep a clear list of which clients are proxied. If you need SOCKS instead, the equivalent properties are socksProxyHost and socksProxyPort, and ProxyGrove plans include SOCKS5 as well as HTTP.

OkHttp and Apache HttpClient

With OkHttp, build one shared client and set both the proxy and a proxy authenticator:

OkHttpClient client = new OkHttpClient.Builder()
    .proxy(new Proxy(Proxy.Type.HTTP, new InetSocketAddress("PROXY_HOST", 8080)))
    .proxyAuthenticator((route, response) -> response.request().newBuilder()
        .header("Proxy-Authorization", Credentials.basic("PROXY_USER", "PROXY_PASS"))
        .build())
    .connectTimeout(Duration.ofSeconds(10))
    .build();

Apache HttpClient 5 uses an HttpHost for the proxy and a credentials provider scoped to that host. In every library, reuse one client per proxy profile so connection pooling works, and close responses so sockets return to the pool.

Sticky versus rotating sessions in Java services

Session behavior is a plan and endpoint setting, not something to rebuild in application code. If your endpoint is sticky, one client instance keeps one exit for the session window, which suits multi-step checks. If the endpoint rotates, each new connection may use a different exit, so do not also shuffle a list of proxies in your code. Pick the mode on the plan, then run one client per profile. The tradeoffs are described in sticky vs rotating proxies.

ProxyGrove currently lists Residential and Corporate from $2 per IP per day and Mobile from $4.50 per IP per day, with 1, 7, 30 and 90 day terms, HTTP and SOCKS5, sticky or rotating sessions and fair-use unlimited traffic on the plan. Confirm live numbers on pricing.

Concurrency, pools and retries

Most proxy trouble in Java services comes from how many requests run at once, not from the proxy setting itself. Size a bounded executor to the number of parallel requests your target tolerates, and begin small. A fixed pool of ten workers per proxy profile is easier to reason about than an unbounded stream of virtual threads, and you can raise it step by step while you watch the success rate.

Retries need a policy. Retry network timeouts and 5xx responses with exponential backoff and a hard cap, add random jitter so workers do not retry in lockstep, and never retry a 407 or a 403 in a tight loop. Treat 429 as a signal to slow down, and honor a Retry-After header when the server sends one.

Keep proxy profiles separate in code. A profile is a small object holding the endpoint, credentials, session mode and a label such as us-residential-sticky. Build one client per profile at startup, hand it to the workers that need it, and log the profile label with every request. When something breaks at three in the morning, a label in the log tells you which pool misbehaved without reading any configuration.

Finally, keep response handling cheap. Read only the bytes you need, set a maximum body size, and discard anything you do not parse. That keeps memory flat under load and keeps your own bandwidth usage predictable, even when the plan itself does not meter traffic.

A short verification routine

  1. Request an IP-echo endpoint through the client and confirm the address differs from your server's own IP.
  2. Repeat twice with a sticky endpoint and confirm the address stays the same inside the window.
  3. Call an internal URL from the same application and confirm it does not go through the proxy.
  4. Force a wrong password and confirm your code surfaces the 407 clearly instead of retrying forever.
  5. Log the status code, latency and exit IP for each request so failures are explainable later.

Common mistakes

  • Using global properties in a shared service. Scope the proxy to the client that needs it.
  • Forgetting timeouts. A hung connection ties up a thread and hides the real fault.
  • Hard-coding credentials. Read them from environment variables or a secret store.
  • Creating a client per request. This defeats pooling and slows everything down.
  • Retrying a 407 blindly. A repeated authentication failure is a configuration problem, not a transient error.

Related reading and next steps

Related engineering posts: Go, cURL, Selenium and Python. When you are ready, open pricing or register at app.proxygrove.com, and pick residential, mobile or corporate. Only collect public data and respect the terms of the sites you call.

ProxyGrove Editorial

Written and maintained by the ProxyGrove Editorial team. Last updated November 15, 2026.

Questions this article answers