OkHttp proxy authentication: 407 and proxyAuthenticator
For an https:// URL, OkHttp sends the proxy login only through a proxyAuthenticator. A Proxy-Authorization header on the request goes into the tunnel, to the website.
In short
Give the client a .proxyAuthenticator that adds Proxy-Authorization: Credentials.basic(user, pass) and returns null when the request already carries that login. OkHttp calls it before every CONNECT, so the login goes out on the first try, and a wrong password fails once instead of 21 times.
java.net.Proxy holds a type and an address, nothing else. OkHttp takes the proxy login from a separate place: the proxyAuthenticator on the client builder. Its default, Authenticator.NONE, never sends anything. The usual first attempt is to add a Proxy-Authorization header to the Request instead, and that works only half the time.
For an https:// URL, OkHttp first asks the proxy for a tunnel with a CONNECT request that it builds itself. Your request, headers included, is sent later, encrypted, through that tunnel to the website. The proxy never sees your header, answers the CONNECT with 407, and OkHttp throws IOException: Failed to authenticate with proxy. For an http:// URL there is no tunnel: the request goes to the proxy as it is, header and all, and the login works. That is why the same code passes one test and fails the next.
OkHttp’s documentation describes the fix. Before every CONNECT it calls the proxy authenticator with a made up 407 whose challenge is OkHttp-Preemptive, so the authenticator can add the login before the proxy asks. After a real 407 it calls it again. Whatever request the authenticator returns is sent; null means give up.
| Where the login is set | http:// URL | https:// URL |
|---|---|---|
| Header on the Request | sent to the proxy | sent to the website; proxy says 407 |
| proxyAuthenticator on the client | sent after the 407 | sent with the CONNECT |
What does each OkHttp proxy error mean?
The messages come from OkHttp's source; the statuses 403 and 465 are our gateway's answers.
| Message | When OkHttp throws it | Fix |
|---|---|---|
| IOException: Failed to authenticate with proxy | The CONNECT got 407 and the proxyAuthenticator returned null: none was set, or it gave up on a refused login | Set a proxyAuthenticator; copy the login again |
| ProtocolException: Too many tunnel connections attempted: 21 | The authenticator kept sending a login the proxy refused, for an https:// URL | Fix the login; return null when it was already sent |
| ProtocolException: Too many follow-up requests: 21 | The same loop for an http:// URL | Same as above |
| IOException: Unexpected response code for CONNECT: 403 | The proxy answered the CONNECT with a status other than 200 or 407 | Our gateway: a value in the username it can’t read |
| IOException: Unexpected response code for CONNECT: 465 | As above | Our gateway: no exit matches the filters |
A wrong password, retried 21 times
Many examples return the credential unconditionally. With a correct login that is fine. With a wrong one, OkHttp sends it, gets 407, asks the authenticator again, sends the same login again, and stops at its limit with Too many tunnel connections attempted: 21. The OkHttp docs recommend checking whether the request already carried a login and returning null if so; then a wrong password ends in a single Failed to authenticate with proxy.
403: a value in the username
Targeting goes into the proxy username: USER-country-de, -city-berlin, -session-job1-lifetime-10. Our gateway refuses values it can’t read with 403: a three letter country code, a city with a space, or a session on the rotating port 9000. OkHttp reports it as an unexpected CONNECT code.
465: no exit for these filters
The login and the username are fine, but no residential exit matches every filter right now. Drop the narrowest one, usually the city. The same three codes in other clients: Java’s HttpClient, C# HttpClient, curl.
For http:// URLs, the 407 is a response
Without a tunnel, a proxy refusal is an ordinary HTTP response. If the authenticator returns null, execute() returns normally with code() == 407, and a gateway 403 looks exactly like a website’s 403. Check the code before you read the body.
A setup that works
Java with OkHttp. PROXY_USER and PROXY_PASS come from the environment; the host and ports are the ones in your dashboard.
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Proxy;
import okhttp3.Credentials;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
public class ProxyFetch {
public static void main(String[] args) throws IOException {
String user = System.getenv("PROXY_USER") + "-country-de";
String pass = System.getenv("PROXY_PASS");
String credential = Credentials.basic(user, pass);
OkHttpClient client = new OkHttpClient.Builder()
.proxy(new Proxy(Proxy.Type.HTTP, new InetSocketAddress("via.proxies.vision", 9000)))
// Called before every CONNECT, and again after each 407 from the proxy.
.proxyAuthenticator((route, response) -> {
if (credential.equals(response.request().header("Proxy-Authorization"))) {
return null; // this login was already refused: stop instead of retrying
}
return response.request().newBuilder()
.header("Proxy-Authorization", credential)
.build();
})
.build();
Request request = new Request.Builder().url("https://ipinfo.io/json").build();
try (Response response = client.newCall(request).execute()) {
System.out.println(response.code() + " " + response.body().string());
}
}
}The authenticator follows the pattern in the documentation of OkHttp’s Authenticator interface. Keep the login out of logs; the Proxy-Authorization value is only Base64, not encrypted.
OkHttp can also connect through SOCKS5 (Proxy.Type.SOCKS), but the proxy authenticator plays no part there: it answers HTTP 407 challenges, which a SOCKS5 proxy never sends. With OkHttp, use the HTTP port. If a SOCKS5 client elsewhere fails, the General SOCKS server failure guide explains its codes.
Port 9000 gives a new exit for every new connection, not for every request. OkHttp keeps connections open for reuse: by default its ConnectionPool holds up to 5 idle connections for 5 minutes. Requests that reuse a pooled connection reuse its tunnel, and with it the exit IP.
A new IP per request
Don’t keep idle connections: .connectionPool(new ConnectionPool(0, 1, TimeUnit.SECONDS)) on the builder (imports okhttp3.ConnectionPool and java.util.concurrent.TimeUnit). With zero idle connections allowed, OkHttp closes each connection when its request is done, and the next one opens a new tunnel.
The same IP on purpose
Put a session label into the username and use the sticky port 10000: USER-country-de-session-job1-lifetime-10 keeps one exit for 10 minutes (up to 1440), across connections. A new label gives a new IP. More on how rotation works in clients that pool connections: rotating proxies in Python, Go’s net/http.
How do I set a proxy with username and password in OkHttp?
Why does OkHttp say 'Failed to authenticate with proxy'?
Why doesn't a Proxy-Authorization header on the Request work for HTTPS?
What does 'Too many tunnel connections attempted: 21' mean?
Does OkHttp's proxyAuthenticator work with SOCKS5?
Keep reading
Node.js fetch Proxy: undici ProxyAgent, NODE_USE_ENV_PROXY
Node's fetch ignores HTTPS_PROXY. Three ways to proxy it, the undici 8 'invalid onRequestStart method' trap, and where the proxy's 407 hides.
6 min read · #node.js#errors
Go net/http Proxy Authentication: HTTP and SOCKS5
Authenticated HTTP and SOCKS5 proxies in Go without extra packages, why rotation needs DisableKeepAlives, and a code generator.
6 min read · #go#authentication
C# HttpClient Proxy Authentication: 407 With the Right Login
Why HttpClient gets 407 from a proxy with the correct login: WebProxy ignores user:pass in its address. Where the credentials go, SOCKS5, and errors.
5 min read · #errors#authentication
Residential proxies, pay per GB
HTTP and SOCKS5. Country, city and sticky sessions in the username. No subscription.