Java Proxy Setup: HttpClient, Authentication and SOCKS

Java proxy configuration depends on the client that opens the connection. For java.net.http.HttpClient, begin with an explicit ProxySelector, a connection timeout and a request timeout. A SOCKS endpoint requires a client and configuration path that actually support SOCKS; an HTTP proxy example is not a SOCKS recipe.

Set a proxy on the Java HttpClient that sends the request

Create one HttpClient for a consistent proxy configuration and reuse it for that route. Set the selector with HttpClient.newBuilder().proxy(ProxySelector.of(new InetSocketAddress(host, port))). Add a connect timeout to the builder and a timeout to the HttpRequest. Read Oracle’s HttpClient builder reference for the API contract.

Save the full example as ProxyCheck.java. Set PROXY_HOST and PROXY_PORT using your provider’s HTTP endpoint. If your proxy uses username and password, inject PROXY_USER and PROXY_PASSWORD from protected configuration. Leave both credentials unset for a source-IP allowlist.

import java.io.IOException;
import java.net.Authenticator;
import java.net.InetSocketAddress;
import java.net.PasswordAuthentication;
import java.net.ProxySelector;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.net.http.HttpTimeoutException;
import java.time.Duration;

public final class ProxyCheck {
    public static void main(String[] args) throws InterruptedException {
        String host = System.getenv("PROXY_HOST");
        String portValue = System.getenv("PROXY_PORT");
        if (host == null || host.isBlank() || portValue == null) {
            throw new IllegalArgumentException("Set PROXY_HOST and PROXY_PORT");
        }
        int port = Integer.parseInt(portValue);
        String user = System.getenv("PROXY_USER");
        String password = System.getenv("PROXY_PASSWORD");
        if ((user == null) != (password == null)) {
            throw new IllegalArgumentException("Supply both proxy credentials or neither");
        }

        HttpClient.Builder builder = HttpClient.newBuilder()
            .proxy(ProxySelector.of(new InetSocketAddress(host, port)))
            .connectTimeout(Duration.ofSeconds(5))
            .followRedirects(HttpClient.Redirect.NEVER);
        if (user != null) {
            builder.authenticator(new Authenticator() {
                @Override
                protected PasswordAuthentication getPasswordAuthentication() {
                    if (getRequestorType() == RequestorType.PROXY
                            && host.equalsIgnoreCase(getRequestingHost())
                            && port == getRequestingPort()) {
                        return new PasswordAuthentication(user, password.toCharArray());
                    }
                    return null;
                }
            });
        }

        URI target = URI.create(args.length == 0 ? "https://api64.ipify.org" : args[0]);
        HttpRequest request = HttpRequest.newBuilder(target)
            .timeout(Duration.ofSeconds(15))
            .GET()
            .build();
        try {
            HttpResponse<String> response = builder.build()
                .send(request, HttpResponse.BodyHandlers.ofString());
            int status = response.statusCode();
            System.out.println("HTTP " + status);
            if (status < 200 || status >= 300) {
                System.exit(1);
            }
            System.out.println(response.body().strip());
        } catch (HttpTimeoutException error) {
            System.err.println("Request timed out");
            System.exit(1);
        } catch (IOException error) {
            System.err.println("Request failed: " + error.getClass().getSimpleName());
            System.exit(1);
        }
    }
}
javac --release 11 ProxyCheck.java
java ProxyCheck

The program requests the public exit IP over HTTPS by default. Pass another URL as an argument to test a small diagnostic endpoint you control. Compare the response with your provider’s expected egress IP before using the same client configuration for an API request.

Keep proxy credentials separate from target credentials

The per-client Authenticator returns credentials only for a PROXY challenge from the configured host and port. Send the target API token on the target request. The sample prints a status or an exception type so proxy credentials stay out of the diagnostic output.

An HTTPS destination through an HTTP proxy begins with a CONNECT request. The JDK 21 distribution used for this guide disables Basic authentication for that tunnel by default. If plain HTTP succeeds but HTTPS returns 407, check jdk.http.auth.tunneling.disabledSchemes in the JDK and confirm which schemes your proxy supports. Source-IP allowlisting is an option for a Basic-only HTTP endpoint when your security policy disallows Basic for CONNECT. See Oracle’s networking properties.

In an isolated test with synthetic credentials, this command starts a separate JVM with Basic tunneling enabled. Use it only when the environment’s policy permits that change. Basic credentials on a plain HTTP proxy connection are encoded and travel without TLS to the proxy.

java -Djdk.http.auth.tunneling.disabledSchemes= ProxyCheck

Which Java clients support HTTP and SOCKS proxies?

Do not infer SOCKS support from the fact that the JVM has networking properties or a Proxy.Type.SOCKS enum. Check the particular library and connection API. Document whether hostname resolution happens locally or on the proxy. The HTTP versus SOCKS5 comparison helps choose the required protocol before writing code.

Can I reuse a SOCKS example with Java HttpClient? Check which Java networking class the example constructs. A SOCKS configuration for a java.net.Socket and an HTTP proxy configuration for java.net.http.HttpClient are different client paths. For a required SOCKS5 route, verify documented support in the client that will actually send the traffic.

Classify the result before retrying

Separate failures to connect, connection timeouts, interrupted requests and completed HTTP responses. A destination 403 or 429 is not automatically a dead proxy, and a 407 is a proxy authentication response. An authentication exchange can also end in IOException before the client returns a response. Check the proxy’s CONNECT status and the destination’s logs independently. Record the status, elapsed time and redacted endpoint identity. Retry only where the operation and policy allow it, with a small budget and backoff.

Test the proxy from the JVM that runs the application

Use a controlled IP-check URL first and validate the response content, not just a 200 status. Repeat the test from the same host that will run the application, then test the intended API. An online checker uses its own route. Keep TLS verification enabled, bound concurrency and retain the original failure category when escalating. See proxy-aware API testing for a test plan.

Example verification. Compiled for Java 11 and ran on Temurin JDK 21.0.11. Seven local checks used synthetic credentials and a loopback proxy. They covered HTTP Basic, bad credentials, an origin challenge, a no-password route, default CONNECT policy, and accepted and rejected TLS trust. The successful HTTPS test used a truststore supplied only to its JVM.

For another implementation, see the Rust proxy guide with reqwest.

Frequently asked questions

Why do proxy requests timeout?

The proxy may be offline, slow, blocked, or configured with the wrong protocol or authentication.

Should I rotate proxies on every request?

Not always. Rotation should match the task. Sessions often need stable IPs.

How do I debug proxy code?

Start with one proxy, one simple URL, verbose logging, and short timeouts.

Do JVM proxy properties affect every Java library?

No. Each client may use its own connection and proxy configuration.

Is a connection timeout a total request deadline?

No. Configure the request timeout separately and understand the client's timeout contract.

Should I disable TLS checks to fix proxy errors?

No. Investigate the certificate chain and connection path instead.

Scroll to Top