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.

6 min read
In OkHttp, a Proxy-Authorization header on the request is not sent with the CONNECT for an HTTPS URL, so the proxy answers 407; a proxyAuthenticator adds the login to the CONNECT itself.Same login, two places to put it, one https:// URLnew Request.Builder() .header("Proxy-Authorization", credential)IOException: Failed to authenticate with proxynew OkHttpClient.Builder() .proxyAuthenticator(...)login sent with the CONNECTOkHttp Authenticator and ConnectPlan, as published by Square

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.

.proxyAuthenticator(...)Credentials.basic(user, pass)

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 sethttp:// URLhttps:// URL
Header on the Requestsent to the proxysent to the website; proxy says 407
proxyAuthenticator on the clientsent after the 407sent with the CONNECT
Fig. 1 — Where OkHttp sends a proxy login, by URL scheme. From OkHttp's Authenticator documentation and its connection code.

What does each OkHttp proxy error mean?

The messages come from OkHttp's source; the statuses 403 and 465 are our gateway's answers.

MessageWhen OkHttp throws itFix
IOException: Failed to authenticate with proxyThe CONNECT got 407 and the proxyAuthenticator returned null: none was set, or it gave up on a refused loginSet a proxyAuthenticator; copy the login again
ProtocolException: Too many tunnel connections attempted: 21The authenticator kept sending a login the proxy refused, for an https:// URLFix the login; return null when it was already sent
ProtocolException: Too many follow-up requests: 21The same loop for an http:// URLSame as above
IOException: Unexpected response code for CONNECT: 403The proxy answered the CONNECT with a status other than 200 or 407Our gateway: a value in the username it can’t read
IOException: Unexpected response code for CONNECT: 465As aboveOur 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.

ProxyFetch.java
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?
Set the proxy with OkHttpClient.Builder().proxy(new Proxy(Proxy.Type.HTTP, new InetSocketAddress(host, port))) and the login with .proxyAuthenticator(...), returning the request with a Proxy-Authorization header built by Credentials.basic(user, pass). java.net.Proxy has no field for a username or password.
Why does OkHttp say 'Failed to authenticate with proxy'?
The proxy answered the CONNECT for an https:// URL with 407 and the proxyAuthenticator returned null. Either no proxyAuthenticator is set (the default, Authenticator.NONE, never sends a login), or yours gave up because the proxy refused the login it sent.
Why doesn't a Proxy-Authorization header on the Request work for HTTPS?
For an https:// URL, OkHttp first opens a tunnel with its own CONNECT request, and only the proxyAuthenticator can add headers to it. Headers on your Request travel inside the tunnel to the website. For http:// URLs there is no tunnel, which is why the same header seems to work there.
What does 'Too many tunnel connections attempted: 21' mean?
Your proxyAuthenticator kept answering the proxy's 407 with the same refused login until OkHttp's limit. The login is wrong. Return null when the request already carries the credential you would add, so a wrong password fails once with a clear error.
Does OkHttp's proxyAuthenticator work with SOCKS5?
No. It answers HTTP 407 challenges, and a SOCKS5 proxy never sends one. With OkHttp, use the proxy's HTTP port: on our gateway via.proxies.vision:9000, or 10000 for sticky sessions, with the same login.

Residential proxies, pay per GB

HTTP and SOCKS5. Country, city and sticky sessions in the username. No subscription.