By GlobalProxyIP Editorial Team
OkHttp and JDK HttpClient both support explicit HTTP proxy routing, but they expose different authentication and lifecycle APIs. Use proxyAuthenticator in OkHttp and a carefully scoped java.net.Authenticator with the JDK client. Do not transplant code between these APIs or confuse JDK HttpClient with Apache HttpClient.
Map each setting to its actual API
| Concern | OkHttp 4.12.0 | JDK 21 HttpClient |
|---|---|---|
| Fixed HTTP proxy | Builder.proxy(new Proxy(...)) |
Builder.proxy(ProxySelector.of(...)) |
| Proxy authentication | proxyAuthenticator |
Client-level authenticator |
| Connection timeout | connectTimeout |
connectTimeout |
| Request timing | callTimeout, plus phase settings |
HttpRequest.timeout, plus connection setting |
| Redirect control | followRedirects and followSslRedirects |
followRedirects |
| Lifecycle | Reuse client; release retired pool/executor appropriately | Reuse client; JDK 21 supports close/shutdown APIs |
Timeout controls have different semantics. Matching their numeric values does not prove equivalent behavior under retries, redirects, body streaming, or multiple addresses.
Use an explicit proxy and bounded authentication
The following JDK 21 program needs Maven dependency com.squareup.okhttp3:okhttp:4.12.0. Provide PROXY_HOST, PROXY_PORT, and TARGET_URL. Supply PROXY_USER and PROXY_PASSWORD together through protected runtime configuration when required; omit both only for a valid no-password authorization mode. Run with jdk or okhttp as the single argument.
import java.net.*;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;
import java.util.concurrent.TimeUnit;
import okhttp3.*;
public class ProxyCheck {
public static void main(String[] args) throws Exception {
String host=System.getenv("PROXY_HOST");
int port=Integer.parseInt(System.getenv("PROXY_PORT"));
String target=System.getenv("TARGET_URL");
String user=System.getenv("PROXY_USER");
String password=System.getenv("PROXY_PASSWORD");
if(host==null || host.isBlank() || port<1 || port>65535 || target==null) throw new IllegalArgumentException("missing configuration");
if ((user==null)!=(password==null)) throw new IllegalArgumentException("incomplete credentials");
if(args.length!=1) throw new IllegalArgumentException("choose jdk or okhttp");
try {
if(args[0].equals("jdk")) {
HttpClient.Builder b=HttpClient.newBuilder()
.proxy(ProxySelector.of(new InetSocketAddress(host,port)))
.connectTimeout(Duration.ofSeconds(5)).followRedirects(HttpClient.Redirect.NEVER);
if(user!=null) b.authenticator(new java.net.Authenticator(){
protected PasswordAuthentication getPasswordAuthentication(){
if(getRequestorType()==RequestorType.PROXY && host.equalsIgnoreCase(getRequestingHost()) && port==getRequestingPort())
return new PasswordAuthentication(user,password.toCharArray());
return null;
}
});
try(HttpClient c=b.build()) {
HttpRequest q=HttpRequest.newBuilder(URI.create(target)).timeout(Duration.ofSeconds(20)).GET().build();
HttpResponse<Void> r=c.send(q,HttpResponse.BodyHandlers.discarding());
System.out.println("status="+r.statusCode());
if(r.statusCode()!=200) System.exit(1);
}
} else if(args[0].equals("okhttp")) {
OkHttpClient.Builder b=new OkHttpClient.Builder()
.proxy(new Proxy(Proxy.Type.HTTP,new InetSocketAddress(host,port)))
.connectTimeout(5,TimeUnit.SECONDS).callTimeout(20,TimeUnit.SECONDS)
.followRedirects(false).followSslRedirects(false).retryOnConnectionFailure(false);
if(user!=null)b.proxyAuthenticator((route,response)->{
if(response.request().header("Proxy-Authorization")!=null)return null;
return response.request().newBuilder().header("Proxy-Authorization",Credentials.basic(user,password)).build();
});
OkHttpClient c=b.build();
try(Response r=c.newCall(new Request.Builder().url(target).get().build()).execute()) {
System.out.println("status="+r.code());
if(r.code()!=200)System.exit(1);
} finally {c.connectionPool().evictAll();c.dispatcher().executorService().shutdown();}
} else throw new IllegalArgumentException("choose jdk or okhttp");
} catch(java.io.IOException e) {System.err.println("request_failed type="+e.getClass().getSimpleName());System.exit(1);}
}
}
Use a controlled small endpoint that returns 200. The example checks status and deliberately avoids printing credential-bearing exceptions. Add response-schema checks in the business layer and confirm proxy use at the target or in proxy access records.
Understand the CONNECT boundary
OkHttp invokes its proxy authenticator before CONNECT using a synthetic authentication challenge. CONNECT is not a normal application request and does not pass through ordinary application interceptors. That is why a general interceptor is the wrong place to implement tunnel authentication.
The callback above returns null when the request already contains a proxy credential and authentication still fails. Without a stopping condition, a simplistic callback can repeatedly submit the same rejected credential.
The JDK implementation applies separate restrictions to authentication schemes for ordinary proxying and CONNECT tunneling. Check jdk.http.auth.proxying.disabledSchemes and jdk.http.auth.tunneling.disabledSchemes in the deployed runtime. An Authenticator callback does not override these policies. Use an authentication method compatible with the deployment’s approved configuration instead of disabling restrictions as a default fix.
Keep client settings local to the component
A JVM-wide proxy selector or global authenticator can affect unrelated libraries. Prefer component-level configuration for services with multiple outbound routes. Reuse each configured client for its intended workload; the command-line cleanup in the example is not a recommendation to destroy the client after every production request.
Record the Java distribution and patch version, dependency version, proxy scheme, authentication mode, target scheme, and redacted failure stage. A result from one runtime configuration does not establish compatibility with every Java deployment.
Frequently asked questions
Is a 401 response a proxy authentication error?
Usually it is the target’s authentication challenge; proxy authentication uses 407. Determine which hop produced the response before changing credentials.
Does OkHttp newBuilder create a completely isolated pool?
Not by default. Its documented behavior shares important resources, including the connection pool. Create and manage deliberately separate resources when isolation is a requirement.
Can a client close operation interrupt work?
Lifecycle methods have different shutdown semantics. Stop new submissions, handle in-flight work, then release resources using the API appropriate to the chosen version.
References
- JDK 21 HttpClient builder
- JDK HTTP client system properties
- OkHttp 4.12 Authenticator
- OkHttp client reuse and newBuilder
Related concepts
For protocol selection, compare HTTP proxy forwarding and SOCKS5 negotiation; for HTTPS through an HTTP endpoint, review the separate CONNECT tunnel stage.