How to Use a Proxy in Java: HttpClient, OkHttp and SOCKS5

Published:

16 minute read

Acar Diveroli
Written by: Acar Diveroli
A line from a Java app crosses a dotted proxy ellipse and turns blue to the target; a dashed first try stops at it with 407

Your Java service has to reach an API through a proxy: a partner only accepts requests from a whitelisted address, a price check must come from another country, or the company network allows nothing out without the corporate proxy. You add the proxy host and port, the username and password are definitely right, and every HTTPS call still fails with 407 Proxy Authentication Required. That is not a typo in your code. By default the JDK refuses to send Basic credentials when it opens an HTTPS tunnel through a proxy, and almost every Java proxy question starts there.

This guide covers the three places Java reads a proxy from: the builder of java.net.http.HttpClient, the -D system properties and a java.net.Proxy object for HttpURLConnection. Then it shows proxy authentication with Authenticator, the jdk.http.auth.tunneling.disabledSchemes property that causes the 407, SOCKS5 (which the built-in HttpClient does not support), OkHttp 5.5.1 and Apache HttpClient 5.6.5, a check of the exit IP and a fetcher with timeouts and retries. We tested the JDK behaviour on a Java 8 runtime against a local proxy that requires user:pass and a local SOCKS5 server; the log lines below are from those runs, with the proxy host replaced by pr.proxynet.io:8000. The HttpClient, OkHttp and Apache examples follow the current Javadoc and project examples.

How does Java decide which proxy to use?

Java asks a ProxySelector for every request: you hand the client a fixed one, or the client falls back to ProxySelector.getDefault(), which reads the networking system properties. The answer is a list of java.net.Proxy objects, each of type HTTP, SOCKS or DIRECT. What happens next depends on the client and the target:

  1. The client connects to the proxy, not to the target host.
  2. Plain http:// target through an HTTP proxy. The request goes to the proxy with the full URL in the request line, and credentials travel in a Proxy-Authorization header.
  3. https:// target through an HTTP proxy. The client sends CONNECT host:443; after the proxy's 200, TLS runs inside the tunnel and the proxy sees only host and port. If the proxy answers 407, the client needs credentials for that CONNECT, and this is the step the JDK restricts.
  4. SOCKS proxy. The client opens the connection through a SOCKS5 handshake, logging in with a username and password if the server asks for them.
  5. Credentials come from an Authenticator in the JDK clients, from a proxyAuthenticator in OkHttp and from a CredentialsProvider in Apache HttpClient.

Which Java HTTP clients support a proxy?

All the common ones, but not in the same way. This is what each client does with an HTTP proxy, a SOCKS5 proxy and proxy authentication:

ClientHTTP proxySOCKS5Proxy auth
java.net.http.HttpClient (11+)ProxySelectorIgnored, goes directAuthenticator, Basic only
HttpURLConnectionProxy.Type.HTTPProxy.Type.SOCKSGlobal or per-connection Authenticator
OkHttp 5proxy()Proxy.Type.SOCKSproxyAuthenticator()
Apache HttpClient 5setProxy()Custom socket factoryCredentialsProvider

The two JDK clients share the system properties and the jdk.http.auth.* rules; OkHttp and Apache HttpClient build their own CONNECT request and are not affected by them.

How do you set a proxy in Java 11 HttpClient?

Pass a ProxySelector to the builder. ProxySelector.of(address) returns a selector that uses one HTTP proxy for every request, as the HttpClient.Builder documentation describes; the same page notes that the JDK implementation "currently only supports HTTP Basic authentication":

java
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.time.Duration;

public class ProxyCheck {
    public static void main(String[] args) throws Exception {
        // Basic auth inside the HTTPS tunnel is off by default. Set this before the first request.
        System.setProperty("jdk.http.auth.tunneling.disabledSchemes", "");

        // Keep credentials in the environment, not in the source code.
        String user = System.getenv().getOrDefault("PROXY_USER", "user");
        String pass = System.getenv().getOrDefault("PROXY_PASS", "pass");

        HttpClient client = HttpClient.newBuilder()
                .proxy(ProxySelector.of(new InetSocketAddress("pr.proxynet.io", 8000)))
                .authenticator(new Authenticator() {
                    @Override
                    protected PasswordAuthentication getPasswordAuthentication() {
                        // Answer the proxy only, never a 401 from the target site.
                        if (getRequestorType() != RequestorType.PROXY) {
                            return null;
                        }
                        return new PasswordAuthentication(user, pass.toCharArray());
                    }
                })
                .connectTimeout(Duration.ofSeconds(10))
                .build();

        HttpRequest request = HttpRequest.newBuilder(URI.create("https://api.ipify.org?format=json"))
                .timeout(Duration.ofSeconds(20))
                .build();

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

A client is immutable, so build it once and reuse it; the proxy cannot be changed later. Without .proxy(...) the client uses the default selector, which means the -D properties below. connectTimeout covers only opening a new connection, while the timeout on the request covers the wait for the response, so set both.

Why does Java return 407 when the proxy password is correct?

Because Basic authentication is switched off for HTTPS tunnels by default. The JDK's conf/net.properties file contains the line jdk.http.auth.tunneling.disabledSchemes=Basic, with the comment that Basic "results in effectively the cleartext transmission of the user's password"; you can read it in the OpenJDK net.properties source. Proxy providers authenticate with Basic, so the JDK never answers their challenge for an https:// target. Plain http:// targets are not affected, because the matching jdk.http.auth.proxying.disabledSchemes property is empty.

On our test machine the difference was clear. With the defaults, the Authenticator was never called and the proxy saw one CONNECT without credentials:

text
CONNECT api.ipify.org:443 proxy-authorization=none user-agent=Java/1.8.0_503 -> 407
java.io.IOException: Unable to tunnel through proxy. Proxy returns "HTTP/1.1 407 Proxy Authentication Required"

With the property set to an empty value, Java retried the CONNECT with the header and the tunnel opened:

text
Authenticator asked: type=PROXY protocol=http scheme=basic host=pr.proxynet.io
CONNECT api.ipify.org:443 proxy-authorization=none user-agent=Java/1.8.0_503 -> 407
CONNECT api.ipify.org:443 proxy-authorization=Basic user user-agent=Java/1.8.0_503 -> 200 (tunnel)

There are two ways to set it, and both must take effect before the HTTP classes load:

bash
# On the command line: applies to the whole JVM
java -Djdk.http.auth.tunneling.disabledSchemes="" -jar app.jar
java
// Or as the very first statement of main(), before any library makes a request
System.setProperty("jdk.http.auth.tunneling.disabledSchemes", "");

The JDK reads the value once, when its HTTP classes initialise, so setting it after the first request does nothing. The same property governs java.net.http.HttpClient and HttpURLConnection. Re-enabling Basic is reasonable here: the CONNECT request goes to a proxy you chose, and the target's traffic stays encrypted inside the tunnel. If your proxy offers an IP whitelist, you can avoid the question entirely, since no credentials are sent; the other causes of a 407 are collected in HTTP 407 Proxy Authentication Required.

How do you set a proxy with Java system properties?

Pass -D flags to the JVM, and every client that uses the default ProxySelector picks them up without code changes. The names and defaults are listed in Oracle's Java Networking guide:

PropertyUsed forDefault
http.proxyHost, http.proxyPorthttp:// targetsnone, 80
https.proxyHost, https.proxyPorthttps:// targetsnone, 443
http.nonProxyHostsHosts that go direct, for bothlocalhost|127.*|[::1]
socksProxyHost, socksProxyPortSOCKS for any TCP socketnone, 1080
java.net.useSystemProxiesOperating system settingsfalse

A typical start command for an HTTP proxy with a password:

bash
java -Dhttps.proxyHost=pr.proxynet.io -Dhttps.proxyPort=8000 \
     -Dhttp.proxyHost=pr.proxynet.io -Dhttp.proxyPort=8000 \
     -Dhttp.nonProxyHosts="localhost|127.*|*.internal.example.com" \
     -Djdk.http.auth.tunneling.disabledSchemes="" \
     -jar app.jar

Three rules come up again and again. The https. pair applies only to https:// targets: in our test with only https.proxyHost set, a request to an http:// address went straight out without touching the proxy. http.nonProxyHosts is shared by both schemes, uses | as the separator and accepts * wildcards; quote it on the command line. And there are no standard http.proxyUser or http.proxyPassword properties in the JDK: the password always comes from an Authenticator in code. java.net.useSystemProxies=true reads the proxy configured in Windows, macOS or GNOME, but explicit -D properties win over it and the flag is read once at startup.

How do you use a proxy with HttpURLConnection?

Create a java.net.Proxy and pass it to openConnection. This works on every Java version from 8 on, and it is still what many libraries use underneath:

java
import java.io.InputStream;
import java.net.Authenticator;
import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.net.PasswordAuthentication;
import java.net.Proxy;
import java.net.URI;
import java.nio.charset.StandardCharsets;

public class LegacyProxyCheck {
    public static void main(String[] args) throws Exception {
        System.setProperty("jdk.http.auth.tunneling.disabledSchemes", "");

        // Global authenticator: used by every HttpURLConnection in the JVM.
        Authenticator.setDefault(new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                if (getRequestorType() != RequestorType.PROXY) {
                    return null;
                }
                return new PasswordAuthentication("user", "pass".toCharArray());
            }
        });

        Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("pr.proxynet.io", 8000));
        HttpURLConnection conn = (HttpURLConnection) URI.create("https://api.ipify.org?format=json")
                .toURL().openConnection(proxy);
        conn.setConnectTimeout(10_000);
        conn.setReadTimeout(20_000);

        int status = conn.getResponseCode();
        try (InputStream in = status < 400 ? conn.getInputStream() : conn.getErrorStream()) {
            String body = in == null ? "" : new String(in.readAllBytes(), StandardCharsets.UTF_8);
            System.out.println(status + " " + body);
        }
    }
}

readAllBytes() needs Java 9; on Java 8, read the stream in a loop. From Java 9 on, conn.setAuthenticator(...) sets the credentials for one connection instead of the whole JVM, which matters when two parts of an application use different proxies. A passed Proxy object is used even for localhost, because http.nonProxyHosts applies only to the default selector.

A wrong password is expensive here. In our test, HttpURLConnection asked the Authenticator 20 times and sent 20 CONNECT requests before giving up with the same Unable to tunnel through proxy message, because the retry loop is bounded by http.maxRedirects, which defaults to 20. A gateway that counts failed logins sees all 20. Make the Authenticator return null after the first attempt, for example by counting calls, when you cannot rule out wrong credentials.

How do you use a SOCKS5 proxy in Java?

Not with java.net.http.HttpClient. Its proxy lookup takes the first proxy the selector returns and uses it only if the type is Proxy.Type.HTTP; for a SOCKS entry it connects directly, without an error or a log line. That behaviour is in the JDK source (HttpRequestImpl.retrieveProxy), and the only visible symptom is your own IP at an echo service. For SOCKS5, use HttpURLConnection, OkHttp or a raw Socket.

With HttpURLConnection, the change from the previous example is one line:

java
Proxy socks = new Proxy(Proxy.Type.SOCKS, new InetSocketAddress("pr.proxynet.io", 1080));
HttpURLConnection conn = (HttpURLConnection) URI.create("https://api.ipify.org?format=json")
        .toURL().openConnection(socks);

The credentials are where most SOCKS setups fail. The JDK's SOCKS code asks the default Authenticator with the protocol SOCKS5 and the requestor type SERVER, not PROXY. Our test logged exactly that:

text
Authenticator asked: type=SERVER protocol=SOCKS5 scheme=null host=pr.proxynet.io
[socks5] greeting methods=[0, 2]
[socks5] auth user=user -> OK
[socks5] CONNECT ipv4 172.67.74.152:443

The Authenticator from the HTTP examples, which answers only RequestorType.PROXY, therefore returns null for SOCKS. The JDK then falls back to the operating-system user name with an empty password: our server logged auth user=root password_len=0 -> FAIL, and Java threw java.net.SocketException: SOCKS : authentication failed. Check getRequestingProtocol() instead:

java
Authenticator.setDefault(new Authenticator() {
    @Override
    protected PasswordAuthentication getPasswordAuthentication() {
        // HTTP proxies ask with RequestorType.PROXY, the SOCKS code with protocol "SOCKS5".
        boolean httpProxy = getRequestorType() == RequestorType.PROXY;
        boolean socks = "SOCKS5".equals(getRequestingProtocol());
        if (!httpProxy && !socks) {
            return null;
        }
        return new PasswordAuthentication("user", "pass".toCharArray());
    }
});

The last log line shows a second detail: HttpURLConnection resolved api.ipify.org itself and sent the proxy an IPv4 address, so the DNS lookup happened on your machine and in your network's resolver. OkHttp sends the host name instead, as shown below. -DsocksProxyHost and -DsocksProxyPort make every TCP socket in the JVM use SOCKS, database drivers included, which is rarely what you want; prefer the Proxy object. The protocol itself, including why it has no CONNECT step, is explained in What Is a SOCKS5 Proxy?. Proxynet's SOCKS5 Proxy uses the same username and password as the HTTP port and also carries UDP, which the Java HTTP clients never use.

How do you set a proxy in OkHttp?

Give the builder a java.net.Proxy with proxy() and the credentials with proxyAuthenticator(). The current release is 5.5.1; with Gradle the dependency is com.squareup.okhttp3:okhttp:5.5.1, while Maven projects must use the okhttp-jvm artifact, because the plain okhttp artifact is empty in Maven builds, as the OkHttp README explains.

java
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.time.Duration;
import okhttp3.Credentials;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class OkHttpProxyCheck {
    public static void main(String[] args) throws Exception {
        String credential = Credentials.basic("user", "pass");

        OkHttpClient client = new OkHttpClient.Builder()
                .proxy(new Proxy(Proxy.Type.HTTP, new InetSocketAddress("pr.proxynet.io", 8000)))
                .proxyAuthenticator((route, response) -> {
                    // Already sent credentials and got 407 again: they are wrong, stop here.
                    if (response.request().header("Proxy-Authorization") != null) {
                        return null;
                    }
                    return response.request().newBuilder()
                            .header("Proxy-Authorization", credential)
                            .build();
                })
                .connectTimeout(Duration.ofSeconds(10))
                .callTimeout(Duration.ofSeconds(30))
                .build();

        Request request = new Request.Builder().url("https://api.ipify.org?format=json").build();
        try (Response response = client.newCall(request).execute()) {
            System.out.println(response.code() + " " + response.body().string());
        }
    }
}

OkHttp writes its own CONNECT request, so the jdk.http.auth.tunneling.disabledSchemes property plays no part. Before every CONNECT it also calls the proxy authenticator with a synthetic 407 whose challenge scheme is OkHttp-Preemptive; the authenticator above adds the header on that first call, so the tunnel opens without a wasted round trip. The header(...) != null check is the one OkHttp's documentation recommends against a loop of 407 responses.

For SOCKS5, pass new Proxy(Proxy.Type.SOCKS, new InetSocketAddress("pr.proxynet.io", 1080)) to proxy(). OkHttp then hands the target as an unresolved host name, so the proxy resolves DNS. The proxyAuthenticator is not used for SOCKS: OkHttp opens the connection through the JDK's SOCKS socket, which asks the default java.net.Authenticator, so you need the SOCKS5 branch from the previous section as well. Write java.net.Authenticator in full in that file, because OkHttp has its own Authenticator interface.

What about Apache HttpClient 5?

Apache HttpClient takes the proxy as an HttpHost and the credentials from a CredentialsProvider scoped to the proxy's host and port. The current stable line is 5.6, released as org.apache.httpcomponents.client5:httpclient5:5.6.5; the pattern follows the ClientProxyAuthentication sample on the HttpClient 5.6 examples page:

java
HttpHost proxy = new HttpHost("pr.proxynet.io", 8000);
CredentialsProvider credentials = CredentialsProviderBuilder.create()
        .add(new AuthScope("pr.proxynet.io", 8000), "user", "pass".toCharArray())
        .build();

try (CloseableHttpClient client = HttpClients.custom()
        .setProxy(proxy)
        .setDefaultCredentialsProvider(credentials)
        .build()) {
    String body = client.execute(new HttpGet("https://api.ipify.org?format=json"),
            response -> EntityUtils.toString(response.getEntity()));
    System.out.println(body);
}

Like OkHttp, Apache HttpClient answers the proxy's challenge itself, without the JDK properties. One difference catches people out: a client built with HttpClients.custom() ignores -Dhttps.proxyHost and the other system properties unless you call .useSystemProperties() on the builder, or create the client with HttpClients.createSystem().

How do you check that requests really use the proxy?

Ask an IP echo service which address it sees, once without and once with the proxy. With a working proxy the two lines differ, and the second address belongs to the exit's country:

java
HttpClient direct = HttpClient.newBuilder().proxy(HttpClient.Builder.NO_PROXY).build();
HttpClient proxied = HttpClient.newBuilder()
        .proxy(ProxySelector.of(new InetSocketAddress("pr.proxynet.io", 8000)))
        .authenticator(proxyAuthenticator) // the Authenticator from the first example
        .build();

HttpRequest ip = HttpRequest.newBuilder(URI.create("https://api.ipify.org?format=json")).build();
System.out.println("without proxy: " + direct.send(ip, HttpResponse.BodyHandlers.ofString()).body());
System.out.println("with proxy:    " + proxied.send(ip, HttpResponse.BodyHandlers.ofString()).body());

HttpClient.Builder.NO_PROXY forces a direct connection even when -D properties are set. If both lines show your own address, the usual causes are a SOCKS entry in a selector for HttpClient, only the http. properties set for an https:// target, a host listed in http.nonProxyHosts, or a client built before ProxySelector.setDefault was called.

A complete example: timeouts, retries and a fixed proxy

The program below adds what a long-running job needs: one shared client, connect and request timeouts, retries with exponential backoff and jitter for network errors, 429 and 5xx, Retry-After honoured, and no retry when the proxy rejects the credentials.

java
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.time.Duration;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ThreadLocalRandom;

public class ProxyFetch {
    private static final int MAX_ATTEMPTS = 4; // first try + 3 retries
    private static final Set<Integer> RETRY_STATUS = Set.of(429, 500, 502, 503, 504);

    public static void main(String[] args) throws Exception {
        System.setProperty("jdk.http.auth.tunneling.disabledSchemes", "");

        String host = System.getenv().getOrDefault("PROXY_HOST", "pr.proxynet.io");
        int port = Integer.parseInt(System.getenv().getOrDefault("PROXY_PORT", "8000"));
        String user = System.getenv().getOrDefault("PROXY_USER", "user");
        String pass = System.getenv().getOrDefault("PROXY_PASS", "pass");

        HttpClient client = HttpClient.newBuilder()
                .proxy(ProxySelector.of(new InetSocketAddress(host, port)))
                .authenticator(proxyOnly(user, pass))
                .connectTimeout(Duration.ofSeconds(10))
                .build();

        List<String> targets = args.length > 0
                ? List.of(args)
                : List.of("https://api.ipify.org?format=json", "https://httpbin.org/status/503");

        for (String target : targets) {
            try {
                HttpResponse<String> response = fetch(client, target);
                System.out.println("ok   " + target + " -> " + response.statusCode());
            } catch (IOException e) {
                System.out.println("fail " + target + " -> " + e.getMessage());
            }
        }
    }

    // Credentials for the proxy only; a 401 from a target site is not answered.
    static Authenticator proxyOnly(String user, String pass) {
        return new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return getRequestorType() == RequestorType.PROXY
                        ? new PasswordAuthentication(user, pass.toCharArray())
                        : null;
            }
        };
    }

    static HttpResponse<String> fetch(HttpClient client, String target)
            throws IOException, InterruptedException {
        HttpRequest request = HttpRequest.newBuilder(URI.create(target))
                .timeout(Duration.ofSeconds(30))
                .header("User-Agent", "status-check/1.0 (+mailto:you@example.com)")
                .build();

        IOException lastError = null;
        for (int attempt = 1; attempt <= MAX_ATTEMPTS; attempt++) {
            HttpResponse<String> response;
            try {
                response = client.send(request, HttpResponse.BodyHandlers.ofString());
            } catch (IOException e) {
                // The JDK gives up on rejected proxy credentials after 3 tries; retrying cannot fix them.
                if (String.valueOf(e.getMessage()).contains("authentication")) {
                    throw e;
                }
                lastError = e;
                Thread.sleep(backoff(attempt));
                continue;
            }
            if (response.statusCode() == 407) {
                throw new IOException("proxy rejected the credentials (407): check user:pass or the IP whitelist");
            }
            if (!RETRY_STATUS.contains(response.statusCode()) || attempt == MAX_ATTEMPTS) {
                return response; // 200, 404, 403 ... the caller decides
            }
            // The site asked us to slow down: its Retry-After (in seconds) wins over our schedule.
            long wait = response.headers().firstValue("Retry-After")
                    .map(ProxyFetch::seconds).orElse(backoff(attempt));
            Thread.sleep(wait);
        }
        throw lastError != null ? lastError : new IOException("no response after " + MAX_ATTEMPTS + " attempts");
    }

    // 1, 2, 4 s ... capped at 30 s, plus up to 1 s of jitter so workers do not retry in step.
    static long backoff(int attempt) {
        long base = Math.min(1000L << (attempt - 1), 30_000L);
        return base + ThreadLocalRandom.current().nextLong(1000);
    }

    static long seconds(String value) {
        try {
            return Long.parseLong(value.trim()) * 1000;
        } catch (NumberFormatException e) {
            return 1000; // a date instead of seconds: wait one second
        }
    }
}

The retry set is small on purpose. A 403 or 404 is returned as it is, because another attempt from another exit does not change what the page is. The JDK's own limit for rejected proxy credentials is 3 attempts (jdk.httpclient.auth.retrylimit), after which send throws an IOException whose message reports "too many authentication attempts"; the check on the message stops the loop there. With a Residential Proxy gateway, a new connection can get a new exit IP while a session parameter in the username, built by the panel's Endpoint Generator, keeps one exit for 1 to 60 minutes. HttpClient reuses connections, so requests in a tight loop often leave through the same tunnel and the same IP.

Where this setup is used

  • API clients behind an allowlist, where a partner accepts requests from one static IP and the service must leave through it.
  • Price and availability checks from another country, with the country chosen in the proxy username.
  • Monitoring and QA from outside the company network, so a health check sees a site the way a visitor in another region does.
  • Applications inside a corporate network that reach the internet only through the company proxy.

Common errors and what they mean

  • Unable to tunnel through proxy. Proxy returns "HTTP/1.1 407 Proxy Authentication Required" for an https:// target: Basic is disabled for tunnels, so set jdk.http.auth.tunneling.disabledSchemes to empty; if it is already empty, the credentials or the whitelisted IP are wrong.
  • Status 407 as a normal response for an http:// target: no Authenticator is set, or it returned null for the proxy.
  • IOException reporting "too many authentication attempts" in java.net.http: the proxy rejected the same credentials three times.
  • java.net.SocketException: SOCKS : authentication failed: the Authenticator did not answer the SOCKS5 request, or the SOCKS credentials are wrong.
  • java.net.ConnectException: Connection refused: nothing listens on that host and port, often an HTTP port used as SOCKS or the other way round.
  • HttpConnectTimeoutException: the client could not open a new connection within connectTimeout.
  • The proxy is simply not used: a SOCKS entry in an HttpClient selector, http. properties without the https. pair, a host in http.nonProxyHosts, or an Apache client built without useSystemProperties().

Common mistakes

  • Setting jdk.http.auth.tunneling.disabledSchemes after the first request. The JDK has already read it; use -D or the first line of main.
  • Expecting http.proxyUser to work. The JDK has no such property; use an Authenticator.
  • One Authenticator that only answers RequestorType.PROXY for a SOCKS proxy. SOCKS asks as SERVER with the protocol SOCKS5.
  • Returning the proxy password to every requestor. An Authenticator that ignores the requestor type sends your proxy credentials to any site that asks with a 401.
  • A SOCKS proxy in an HttpClient selector. It is silently ignored.
  • Building a new HttpClient for every request. Each one has its own connection pool and threads; build one and share it.
  • No timeouts. Neither HttpClient nor HttpURLConnection has a request timeout by default, so a silent exit blocks a thread.
  • Disabling certificate checks behind a corporate proxy. Add the company's root certificate to the truststore instead; a provider's gateway never touches the TLS inside the tunnel.

Which approach should you choose?

Your situationRecommendation
Java 11+, one HTTP proxyHttpClient with ProxySelector.of and an Authenticator
HTTPS target with user:pass-Djdk.http.auth.tunneling.disabledSchemes="" or an IP whitelist
No code changes allowed-Dhttps.proxyHost/-Dhttps.proxyPort plus the http. pair
SOCKS5 with DNS at the proxyOkHttp with Proxy.Type.SOCKS
SOCKS5 without extra librariesHttpURLConnection with Proxy.Type.SOCKS
Already on OkHttpproxy() plus proxyAuthenticator()
Already on Apache HttpClientsetProxy() plus a CredentialsProvider
Same exit IP for a login flowA sticky session parameter in the username

Frequently asked questions

How do I set a proxy for one request only in Java?

Use a separate client for it: an HttpClient built with its own ProxySelector, or openConnection(proxy) on that one HttpURLConnection. The -D properties and Authenticator.setDefault apply to the whole JVM.

Does Java 11 HttpClient support SOCKS5?

No. It uses a proxy only if the selector's first entry is of type HTTP and connects directly otherwise. Use HttpURLConnection or OkHttp with Proxy.Type.SOCKS for SOCKS5.

Why is my Authenticator never called?

For an https:// target through an HTTP proxy, the usual reason is the default jdk.http.auth.tunneling.disabledSchemes=Basic: the JDK sees a Basic challenge it is not allowed to answer and does not ask. Set the property to empty before the first request.

Can I put user:pass in the proxy URL in Java?

No. Unlike curl or Go, the JDK clients take a host and port only, and the credentials come from an Authenticator, from OkHttp's proxyAuthenticator or from Apache's CredentialsProvider.

Does Java use the Windows proxy settings?

Only with -Djava.net.useSystemProxies=true, which reads the operating system's proxy at startup; explicit -D proxy properties still win over it.

Is this the same as the Proxy design pattern?

No. The design pattern and java.lang.reflect.Proxy are about objects that stand in for other objects inside a program; this guide is about network proxies that carry HTTP and SOCKS traffic to another server.

Summary

In Java the proxy is either a ProxySelector on java.net.http.HttpClient, a java.net.Proxy passed to HttpURLConnection or OkHttp, or the -D system properties read by the default selector. Credentials come from an Authenticator, and for HTTPS targets the JDK only sends Basic credentials after jdk.http.auth.tunneling.disabledSchemes is set to empty, which is the reason behind most 407 errors. SOCKS5 needs HttpURLConnection or OkHttp, an Authenticator that answers the SOCKS5 request, and OkHttp if the proxy should resolve DNS. Residential, static ISP, datacenter and SOCKS5 endpoints that work with these settings are on the Proxynet proxy page.

Ask ChatGPTAsk Claude