Getting Java's HttpClient to authenticate to a proxy
By the ProxyV4 Engineering Team · Updated:
Java HttpClient proxy authentication needs two pieces: a ProxySelector that points at the proxy and an Authenticator that returns the username and password when getRequestorType() is PROXY. For HTTPS URLs there is a third: since Java 8u111 the JDK refuses Basic credentials on CONNECT tunnels unless you clear jdk.http.auth.tunneling.disabledSchemes. Miss that property and your authenticator is never called, and every HTTPS request ends in 407.
Why your Authenticator is skipped on HTTPS URLs
The JDK ships with jdk.http.auth.tunneling.disabledSchemes=Basic in its net.properties file. The setting applies to proxy authentication during HTTPS tunneling: when the proxy answers a CONNECT with 407 and offers Basic, the JDK treats Basic as disabled and gives up instead of asking your Authenticator. Plain http:// URLs are governed by a separate property, jdk.http.auth.proxying.disabledSchemes, which is empty by default, so those requests authenticate fine.
That asymmetry is the usual source of confusion: the same code works for http:// targets and fails for https:// ones. Almost every commercial proxy uses Basic, so the default has to change for HTTPS to work.
A working java.net.http setup
This is a complete Java 11+ program. It clears the property, configures the proxy and returns credentials only to the proxy, never to the destination site:
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 ProxyDemo {
public static void main(String[] args) throws Exception {
// Must run before the first HttpClient is created.
System.setProperty("jdk.http.auth.tunneling.disabledSchemes", "");
Authenticator proxyAuth = new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
if (getRequestorType() == RequestorType.PROXY) {
return new PasswordAuthentication("USER", "PASS".toCharArray());
}
return null;
}
};
HttpClient client = HttpClient.newBuilder()
.proxy(ProxySelector.of(new InetSocketAddress("203.0.113.10", 8080)))
.authenticator(proxyAuth)
.connectTimeout(Duration.ofSeconds(10))
.build();
HttpRequest req = HttpRequest.newBuilder(URI.create("https://proxyv4.com/api/my-ip"))
.timeout(Duration.ofSeconds(20))
.build();
HttpResponse<String> resp = client.send(req, HttpResponse.BodyHandlers.ofString());
System.out.println(resp.statusCode() + " " + resp.body());
}
}The authenticator is attached to this client only, not installed globally with Authenticator.setDefault, so other clients in the same JVM are unaffected. The RequestorType.PROXY check matters: without it, a site that answers 401 would receive your proxy password.
Setting jdk.http.auth.tunneling.disabledSchemes so it sticks
The JDK reads this property when its HTTP classes initialize, not on every request. Setting it late, after a library has already created an HttpClient or opened an HttpURLConnection, can silently have no effect. Three places work reliably:
- On the command line:
java -Djdk.http.auth.tunneling.disabledSchemes= -jar app.jar. An empty value after=is valid and means no scheme is disabled. - In
JAVA_TOOL_OPTIONSor your container's JVM options, which is convenient when you cannot change the launch command. - As the very first statement of
main, as in the example above, provided nothing earlier in startup touched the networking stack.
Spring Boot and other frameworks
Frameworks often create HTTP clients during context startup, before your configuration code runs. Prefer the -D flag there. If you only clear the property in a @Bean method, the first client may already exist with the default.
Is clearing it safe?
The default exists because Basic sends credentials in base64, which anyone on the path between you and the proxy can read. Clearing the property re-enables Basic only for proxy tunneling, so use a dedicated proxy credential and keep it out of logs; the traffic to the website inside the tunnel is still protected by its own TLS.
OkHttp proxy authenticator
OkHttp does not use the JDK's authentication machinery for HTTP proxies, so disabledSchemes does not apply. You configure the proxy and supply a proxyAuthenticator that adds the header when OkHttp sees a 407 challenge:
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.time.Duration;
import okhttp3.Credentials;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
String credential = Credentials.basic("USER", "PASS");
OkHttpClient client = new OkHttpClient.Builder()
.proxy(new Proxy(Proxy.Type.HTTP, new InetSocketAddress("203.0.113.10", 8080)))
.proxyAuthenticator((route, response) -> {
if (response.request().header("Proxy-Authorization") != null) {
return null; // credentials already rejected; stop retrying
}
return response.request().newBuilder()
.header("Proxy-Authorization", credential)
.build();
})
.callTimeout(Duration.ofSeconds(20))
.build();
try (Response r = client.newCall(new Request.Builder()
.url("https://proxyv4.com/api/my-ip").build()).execute()) {
System.out.println(r.code() + " " + r.body().string());
}The null check prevents a burst of pointless retries when the password is wrong: OkHttp would otherwise resend the same rejected header until it hits its follow-up limit. One OkHttpClient per proxy is the normal pattern; derive variants with client.newBuilder() so they share the connection pool and dispatcher.
Apache HttpClient 5 proxy authentication
Many searches for this error mean Apache HttpClient, not the JDK client. It has its own credential store and never reads jdk.http.auth.tunneling.disabledSchemes, so the Basic-over-CONNECT trap above does not apply. You register the proxy as the route's proxy host and put the login into a BasicCredentialsProvider scoped to that host and port.
Classic client with a proxy login
HttpHost proxy = new HttpHost("http", "IP", PORT);
BasicCredentialsProvider creds = new BasicCredentialsProvider();
creds.setCredentials(new AuthScope(proxy), new UsernamePasswordCredentials("USER", "PASS".toCharArray()));
try (CloseableHttpClient client = HttpClients.custom()
.setProxy(proxy)
.setDefaultCredentialsProvider(creds)
.build()) {
String ip = client.execute(new HttpGet("https://proxyv4.com/api/my-ip"),
response -> EntityUtils.toString(response.getEntity()));
System.out.println(ip);
}Imports come from org.apache.hc.client5.http and org.apache.hc.core5.http. The AuthScope(proxy) scope matters: a scope for the target site instead of the proxy is the most common reason Apache HttpClient keeps returning 407.
When the 407 does not go away
Turn on wire logging for org.apache.hc.client5.http and look for the Proxy-Authorization header on the second CONNECT attempt. If it never appears, the credentials provider is not attached to the client that sends the request, which happens when a shared client is built in one place and a new one without credentials is built in another. Apache HttpClient 4.x uses the same idea with HttpHost("IP", PORT) and AuthScope("IP", PORT).
Java SOCKS proxy options
java.net.http.HttpClient only supports HTTP proxies. A ProxySelector that returns a Proxy.Type.SOCKS entry is not honored, and the request may go out directly without any error, which is the worst possible failure for a proxy setup. Verify the exit IP whenever you experiment here.
The socket-based APIs do support SOCKS5 with a username and password. HttpURLConnection, plain Socket and OkHttp all accept new Proxy(Proxy.Type.SOCKS, address), and the JDK's SOCKS client obtains credentials from the default Authenticator:
Authenticator.setDefault(new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
if ("SOCKS5".equals(getRequestingProtocol())
&& "203.0.113.10".equals(getRequestingHost())) {
return new PasswordAuthentication("USER", "PASS".toCharArray());
}
return null;
}
});
Proxy socks = new Proxy(Proxy.Type.SOCKS, new InetSocketAddress("203.0.113.10", 1080));
HttpURLConnection conn = (HttpURLConnection)
URI.create("https://proxyv4.com/api/my-ip").toURL().openConnection(socks);
System.out.println(conn.getResponseCode());Because SOCKS credentials come from the process-wide authenticator, filter on getRequestingProtocol() and the requesting host so the password is never handed to anything else. If your proxy port speaks both HTTP and SOCKS5, the HTTP route through java.net.http is usually simpler. The protocol trade-offs are in HTTP vs SOCKS5.
Fixed egress IPs for JVM services
Many JVM proxy setups exist for one reason: a partner API, payment gateway or B2B portal only accepts calls from registered addresses, and the service runs in a cloud whose outbound IP changes. Routing that traffic through a private IPv4 gives the integration a fixed source address. With ProxyV4, each private datacenter IPv4 has a single tenant for the whole term, the address stays the same while the proxy is active, and renewing before expiry keeps it, so the address you register with a partner does not drift.
Every paid proxy supports HTTP(S), and private IPv4 outside Vietnam and US static ISP proxies also support SOCKS5 with username and password, with HTTP only, SOCKS5 only or both on the same port chosen per order in the dashboard, which covers both java.net.http and the socket-based SOCKS route. Traffic on private IPv4 is unmetered. IPs are available in the United States, Vietnam, Japan, South Korea, Singapore, the United Kingdom and Hong Kong; live prices are per IP per month, and a single IP is a valid order.
This is not the right setup when you need IPv6 egress, which is a separate IPv6 proxy product, or a pool that changes IP on every call, since rotating proxies are not sold. Order one IP, run the service against it in staging, then roll it out.
Exceptions and status codes by client
Each Java client reports proxy failures differently, so the same misconfiguration looks like three different bugs.
java.net.http
When tunnel authentication fails, the client typically hands back a response with statusCode() of 407 rather than throwing, so check the code before reading the body. A java.net.ConnectException means the proxy address or port is unreachable. Turn on -Djdk.httpclient.HttpClient.log=errors,requests,headers to see whether a Proxy-Authorization header was ever sent.
HttpURLConnection
The classic message is java.io.IOException: Unable to tunnel through proxy. Proxy returns "HTTP/1.1 407 Proxy Authentication Required". With credentials that are definitely correct, that is the disabledSchemes default at work. Otherwise, follow the 407 troubleshooting guide.
OkHttp
OkHttp throws java.io.IOException: Failed to authenticate with proxy when the authenticator returns null or the proxy keeps refusing the tunnel. For a plain HTTP target you instead get a Response with code 407. Tunnel setup problems that are not about credentials are covered on the tunnel connection failed page.
Frequently asked questions
Does Java 11 HttpClient support proxy authentication?
Yes, through HttpClient.Builder.authenticator(). For HTTPS targets with a Basic proxy you must also clear jdk.http.auth.tunneling.disabledSchemes, or the authenticator is never asked for credentials.
Can I just add a Proxy-Authorization header to the HttpRequest?
Not for HTTPS targets. Request headers travel inside the encrypted tunnel, while the proxy needs the header on the CONNECT request, which the request builder does not expose.
Does java.net.http HttpClient support SOCKS5?
No. It only uses HTTP proxies. Use HttpURLConnection, OkHttp or a raw Socket with Proxy.Type.SOCKS, or use the HTTP mode of your proxy.
Does OkHttp need the disabledSchemes property?
Not for HTTP proxies, because OkHttp handles the 407 challenge through its own proxyAuthenticator. For SOCKS proxies it relies on the JDK socket and its default authenticator.
Will the proxy IP change if I renew my ProxyV4 order?
No. The IP stays the same while the proxy is active, and renewing before expiry keeps the same address. You can renew all proxies in an order or only a selection.
Fixed egress IPs for your JVM services
ProxyV4 private IPv4 proxies give each service a single-tenant address with HTTP and SOCKS5 login, unmetered traffic and the same IP on renewal. Order one, test it against your integration, then scale.
Get a static IP