Skip to content

Updated

Java OkHttp Proxy:
HttpClient and OkHttp With Login

  1. In Java HttpClient use .proxy(ProxySelector.of(new InetSocketAddress(host, port))) and an Authenticator that answers only when getRequestorType() is PROXY.
  2. For https:// targets also clear jdk.http.auth.tunneling.disabledSchemes, whose JDK default is Basic.
  3. In OkHttp use .proxy(...) and a proxyAuthenticator that sets Proxy-Authorization with Credentials.basic.

Check it right after buyingExample output

curl -x http://USER:PASS@HOST:PORT https://ipinfo.io/json

ip
203.0.113.24
country
US
Matches the country you picked
Day 15
203.0.113.24
Same address for the whole term
Example addresses (203.0.113.0/24), not real exits
01 / 11Two clients, two ways to give the login

Working code for both clients, plus the one JDK default that makes proxy login fail on https:// sites and the connection settings behind IP rotation.

Two clients, two ways to give the login

Java's built-in HttpClient takes the proxy from a ProxySelector and the login from an Authenticator. OkHttp takes a Proxy object and a proxyAuthenticator that returns a request carrying a Proxy-Authorization header. Both examples use the HTTP port of the proxy and call https://ipinfo.io/json.

The HttpClient example needs one extra line for https:// targets. The OpenJDK net.properties file ships jdk.http.auth.tunneling.disabledSchemes=Basic, and the java.net.http documentation says this property lists schemes the client may not use for CONNECT tunneling. With Basic in that list, the proxy login is never sent and the request fails with a 407.

Java HttpClient (JDK 11 and later)

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;

public class ProxyDemo {
    public static void main(String[] args) throws Exception {
        // Allow Basic proxy login for https:// targets (JDK default disables it for CONNECT tunnels).
        // Set it before the first client is created, or pass -Djdk.http.auth.tunneling.disabledSchemes="" on the command line.
        System.setProperty("jdk.http.auth.tunneling.disabledSchemes", "");

        HttpClient client = HttpClient.newBuilder()
            .proxy(ProxySelector.of(new InetSocketAddress("HOST", 2222)))
            .authenticator(new Authenticator() {
                @Override
                protected PasswordAuthentication getPasswordAuthentication() {
                    if (getRequestorType() == RequestorType.PROXY) {
                        return new PasswordAuthentication("LOGIN", "PASSWORD".toCharArray());
                    }
                    return null;
                }
            })
            .build();

        HttpRequest request = HttpRequest.newBuilder(URI.create("https://ipinfo.io/json")).build();
        System.out.println(client.send(request, HttpResponse.BodyHandlers.ofString()).body());
    }
}

Replace HOST, LOGIN and PASSWORD with the values from My assets. 2222 is the HTTP port.

OkHttp

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

public class OkProxyDemo {
    public static void main(String[] args) throws Exception {
        Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("HOST", 2222));

        Authenticator proxyAuthenticator = (route, response) -> {
            if (response.request().header("Proxy-Authorization") != null) {
                return null; // already tried once: give up instead of looping
            }
            return response.request().newBuilder()
                .header("Proxy-Authorization", Credentials.basic("LOGIN", "PASSWORD"))
                .build();
        };

        OkHttpClient client = new OkHttpClient.Builder()
            .proxy(proxy)
            .proxyAuthenticator(proxyAuthenticator)
            .build();

        Request request = new Request.Builder().url("https://ipinfo.io/json").build();
        try (Response response = client.newCall(request).execute()) {
            System.out.println(response.body().string());
        }
    }
}

OkHttp calls the proxy authenticator before the CONNECT request, so Basic login works for https:// targets without the JDK property. The null return stops a retry loop when the login is wrong.

Connection reuse and rotation

On a rotating gateway the IP is chosen when a connection opens, so requests that reuse a connection keep the same IP. OkHttp's default pool holds up to 5 idle connections for 5 minutes, so a loop of calls can leave from one IP for a while.

To ask for a new IP on the next request, make the client open a new connection: with OkHttp a pool that keeps no idle connections does it. For HttpClient, create a new HttpClient object when you want a new connection. Check the result with ipinfo.io rather than assuming it.

OkHttp: no idle connections kept

// OkHttp: keep no idle connections, so the next request opens a new one
OkHttpClient fresh = client.newBuilder()
    .connectionPool(new ConnectionPool(0, 1, TimeUnit.SECONDS))
    .build();

client is the OkHttpClient from the example above. Needs imports okhttp3.ConnectionPool and java.util.concurrent.TimeUnit.

HttpClient and OkHttp side by side

HttpClient and OkHttp side by side
ItemWhere the proxy goesWhere the login goesWhat to watch
java.net.http.HttpClientBuilder.proxy(ProxySelector.of(...))Builder.authenticator(...), answer when the requestor type is PROXYBasic is disabled for CONNECT tunneling by default
OkHttpBuilder.proxy(new Proxy(Proxy.Type.HTTP, ...))Builder.proxyAuthenticator(...) setting Proxy-AuthorizationReturn null if the header was already sent

From the java.net.http module documentation, OpenJDK net.properties and the OkHttp sources, all read on 20 November 2026.

How to do it with Proxy302

Each snippet needs four values from a Proxy302 proxy: host, port, login and password. For scraping, rotating residential traffic is billed per GB (Budget line US$1.50 per GB, Premium line US$5 per GB); HTTP is on port 2222 and SOCKS5 on port 3333 of proxy.proxy302.com, and the same login works for both. Without a session, each new connection gets a new IP, and a connection you keep open keeps its IP.

When the other side needs one fixed address, a datacenter IP lease costs US$0.25 for 1 day or US$3.99 for 30 days, and you choose HTTP or SOCKS5 when you buy it. There is no free trial; the smallest purchase is 1 GB of rotating residential traffic or one IP for one day.

How to do it with Proxy302: steps

  1. Step 1

    Open the rotating residential page, choose the line, then click Review cost and generate. For a fixed IP, buy a datacenter IP on the datacenter pay-per-IP page instead.

  2. Step 2

    Open My assets and copy HOST, PORT, USERNAME and PASSWORD exactly as they are shown there.

  3. Step 3

    Paste them into the code in this guide, using the port that matches the protocol: 2222 for HTTP, 3333 for SOCKS5.

  4. Step 4

    Run the code against https://ipinfo.io/json and check that the country and org fields describe the proxy, not your own connection.

Troubleshooting

407 Proxy Authentication Required on https:// sites only

Check jdk.http.auth.tunneling.disabledSchemes still contains Basic (the JDK default).

Fix Clear it before the first client is created, or pass it with -D on the command line.

Stop when If a plain http:// target also returns 407, the login itself is wrong: re-copy it from My assets.

Connection refused, timeout or SocketTimeoutException

Check Port matches the protocol (2222 for HTTP), HOST copied correctly, the proxy type is HTTP.

Fix Fix the port or type, then run again; see the connection guide for the other checks.

Stop when If every port times out from your network, test from another network before changing code.

The response shows your own IP

Check No proxy was set on the client that sent the request, or an application-wide ProxySelector is used instead.

Fix Print which client object is used for the call and set the proxy there.

Stop when If a framework builds its own client, configure the proxy in that framework instead.

FAQ

How do I set a proxy with username and password in Java HttpClient?

Use HttpClient.newBuilder().proxy(ProxySelector.of(new InetSocketAddress(host, port))) and .authenticator(...) returning a PasswordAuthentication when getRequestorType() is PROXY.

Why does Java ignore my proxy login for HTTPS sites?

The JDK default for jdk.http.auth.tunneling.disabledSchemes is Basic, so Basic login is not sent on the CONNECT request. Set the property to an empty value to allow it.

How do I add a proxy login in OkHttp?

Set Builder.proxy(...) and a proxyAuthenticator that returns the request with a Proxy-Authorization header built by Credentials.basic(login, password).

Why do my Java requests keep the same IP on a rotating proxy?

Connections are reused, and the IP is chosen when a connection opens. Use a new client or a pool that keeps no idle connections when you want a new IP.

Further reading

Setup guides Proxy302 publishes on GitHub on the same topic:

Reference links

4
  1. Java SE API: java.net.http module

    Official documentation · Confirmed on:

    Read on 20 November 2026: the jdk.http.auth.proxying.disabledSchemes and jdk.http.auth.tunneling.disabledSchemes properties, and that HttpClient.Builder.proxy takes a ProxySelector (ProxySelector.of for one proxy) and authenticator takes an Authenticator.

  2. OpenJDK net.properties

    Official documentation · Confirmed on:

    Read on 20 November 2026: jdk.http.auth.tunneling.disabledSchemes=Basic is the default, and the proxying list is empty.

  3. OkHttp source: Authenticator and OkHttpClient

    Official documentation · Confirmed on:

    Read on 20 November 2026: preemptive authentication before the CONNECT request, reactive authentication on a 407, the advice to give up when a credential was already sent, Builder.proxy and proxyAuthenticator, and the ConnectionPool defaults (5 idle connections, 5 minutes).

  4. Proxy302 product facts and price list

    Product observation · Confirmed on:

    Product facts file of the site (values checked against the console, the backend and the price table): products, prices in US$ (1 PTC = US$1), lease terms, protocols and ports, quantity limits, no free trial.

Ready to try it?

Create an account, top up once, then pick rotating residential, static ISP or datacenter IPs and have one running in your browser within minutes.