Programming languages

How to use a proxy in Java

Java runs many enterprise crawlers, testing tools and Android backends. The java.net.http.HttpClient added in Java 11 supports proxies through a ProxySelector and credentials through an Authenticator, with one catch: Basic authentication for HTTPS tunnels is turned off by default in the JDK.

This guide shows the JDK property that turns it back on, a working HttpClient setup, OkHttp, which handles authentication on its own, and SOCKS5 with HttpURLConnection.

Updated 23 November 2026

What you need
Hostgate.firstproxy.shop
HTTP / HTTPS port8000
SOCKS5 port9000
Usernameuser-country-gb
PasswordYOUR_TOKEN

HttpClient supports HTTP proxies on port 8000. For SOCKS5 on port 9000, use HttpURLConnection or OkHttp. Your username and token appear on the Proxy setup page of your dashboard after your first order.

Setup

How do I connect Java to a proxy?

Follow the steps in order. Replace YOUR_TOKEN with the token from your dashboard and change the country, city or session in the username to suit the job.

  1. Allow Basic authentication for HTTPS tunnels

    Since JDK 8u111 the property jdk.http.auth.tunneling.disabledSchemes defaults to Basic, which blocks username and password authentication on CONNECT tunnels. Without this change every HTTPS request through an authenticated proxy fails with 407. Set it to an empty value when you start the JVM.

    java -Djdk.http.auth.tunneling.disabledSchemes= -jar app.jar
  2. Send a request with HttpClient

    Point a ProxySelector at the gateway and answer proxy authentication requests with your username and token. The check on the requestor type keeps the credentials from being sent to target sites.

    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 Main {
        public static void main(String[] args) throws Exception {
            System.setProperty("jdk.http.auth.tunneling.disabledSchemes", "");
    
            HttpClient client = HttpClient.newBuilder()
                .proxy(ProxySelector.of(new InetSocketAddress("gate.firstproxy.shop", 8000)))
                .authenticator(new Authenticator() {
                    @Override
                    protected PasswordAuthentication getPasswordAuthentication() {
                        if (getRequestorType() != RequestorType.PROXY) return null;
                        return new PasswordAuthentication("user-country-gb", "YOUR_TOKEN".toCharArray());
                    }
                })
                .connectTimeout(Duration.ofSeconds(10))
                .build();
    
            HttpRequest request = HttpRequest.newBuilder(URI.create("https://ipinfo.io/json"))
                .timeout(Duration.ofSeconds(30))
                .build();
            HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
            System.out.println(response.statusCode() + " " + response.body());
        }
    }
  3. Use targeting and a sticky session

    The username is a plain string, so build it per client. One HttpClient per session keeps its connections, and its IP, separate from other sessions.

    static String proxyUser(String country, String city, String session, int ttl) {
        StringBuilder u = new StringBuilder("user-country-").append(country);
        if (city != null) u.append("-city-").append(city);
        if (session != null) u.append("-session-").append(session).append("-ttl-").append(ttl).append("m");
        return u.toString();
    }
    
    String user = proxyUser("gb", "manchester", java.util.UUID.randomUUID().toString().substring(0, 8), 30);
  4. Use OkHttp with a proxy authenticator

    OkHttp builds its own CONNECT requests, so the JDK property is not needed. Its proxyAuthenticator is called when the gateway answers 407 and returns the request with credentials attached.

    // implementation("com.squareup.okhttp3:okhttp:4.12.0")
    import java.net.InetSocketAddress;
    import java.net.Proxy;
    import okhttp3.Credentials;
    import okhttp3.OkHttpClient;
    import okhttp3.Request;
    import okhttp3.Response;
    
    OkHttpClient client = new OkHttpClient.Builder()
        .proxy(new Proxy(Proxy.Type.HTTP, new InetSocketAddress("gate.firstproxy.shop", 8000)))
        .proxyAuthenticator((route, response) -> response.request().newBuilder()
            .header("Proxy-Authorization", Credentials.basic("user-country-gb", "YOUR_TOKEN"))
            .build())
        .build();
    
    try (Response res = client.newCall(new Request.Builder().url("https://ipinfo.io/json").build()).execute()) {
        System.out.println(res.code() + " " + res.body().string());
    }
  5. Connect over SOCKS5

    HttpClient does not support SOCKS proxies. HttpURLConnection does, and the JDK asks the default Authenticator for the SOCKS5 username and password.

    Authenticator.setDefault(new Authenticator() {
        @Override
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication("user-country-gb", "YOUR_TOKEN".toCharArray());
        }
    });
    
    Proxy socks = new Proxy(Proxy.Type.SOCKS, new InetSocketAddress("gate.firstproxy.shop", 9000));
    HttpURLConnection conn = (HttpURLConnection) URI.create("https://ipinfo.io/json").toURL().openConnection(socks);
    conn.setConnectTimeout(10000);
    conn.setReadTimeout(30000);
    System.out.println(new String(conn.getInputStream().readAllBytes()));
Test

How do I check that the proxy works?

Run the HttpClient example and read the printed JSON. A 200 with the expected country means the proxy, the property and the Authenticator are all set correctly.

A working proxy returns a response like the one shown, trimmed to the main fields. The IP belongs to the exit, the city and country follow your username, and the time zone is where that IP is located, here United Kingdom.

java -Djdk.http.auth.tunneling.disabledSchemes= Main.java
ipinfo.io/json response
{
  "ip": "203.0.113.24",
  "city": "London",
  "country": "GB",
  "timezone": "Europe/London"
}

203.0.113.24 is a documentation address. Your result shows a real exit IP.

Targeting

How do I set country, city and session in the username?

All targeting is written into the username, so Java needs no extra settings to change location. Parts are joined with hyphens in this order after your proxy user. The password is always your token.

Proxy username parts
PartFormatExampleRule
Country-country-{cc}-country-gbRequired. Two-letter country code in lowercase. 64 countries are available.
City-city-{city}-city-londonOptional. City name in lowercase, spaces become hyphens. 172 cities are available.
Session-session-{id}-session-a1b2c3Optional. Any letters and digits you choose. The same id keeps the same IP, a new id gets a new IP.
Session length-ttl-{minutes}m-ttl-30mUsed with a session. Residential 1 to 120 minutes, mobile 1 to 60, long-acting ISP up to 720 (12 hours).
Full usernameuser-country-gb-city-london-session-a1b2c3-ttl-30m

Find country codes and city values on the proxy locations page.

Troubleshooting

Java proxy errors and fixes

The problems people run into most often with Java, with the message you are likely to see and how to solve it.

Unable to tunnel through proxy. Proxy returns "HTTP/1.1 407"

Basic is still disabled for tunnels. Pass -Djdk.http.auth.tunneling.disabledSchemes= on the command line, because setting it later in code can be too late once HTTP classes are loaded.

The Authenticator is never called

For HttpClient, attach it with .authenticator() on the builder. For HttpURLConnection, use Authenticator.setDefault. Also check that the method returns credentials for the PROXY requestor type.

HttpConnectTimeoutException or HttpTimeoutException

Set connectTimeout on the client and timeout on each request. Without them a slow exit can block a thread for a long time.

All threads share one IP

Clients reuse connections, so threads that share one client also share tunnels and IPs. Create one client per session name when each thread needs its own IP.

SOCKS proxy ignored by HttpClient

java.net.http.HttpClient only supports HTTP proxies. Use the HTTP port with HttpClient, or HttpURLConnection or OkHttp for SOCKS5.

FAQ

Java proxy questions

Short answers to what people ask most about using a proxy with Java.

Why does my Java proxy return 407 for HTTPS sites only?

The JDK disables Basic authentication for HTTPS tunnels by default. Start the JVM with -Djdk.http.auth.tunneling.disabledSchemes= (an empty value) so the Authenticator can send the username and token.

How do I set a proxy in java.net.http.HttpClient?

Use HttpClient.newBuilder().proxy(ProxySelector.of(new InetSocketAddress("gate.firstproxy.shop", 8000))) and add an Authenticator that returns your username and token for proxy requests.

Does OkHttp need the tunneling property?

No. OkHttp sends its own CONNECT requests and uses its proxyAuthenticator to add the Proxy-Authorization header, so the JDK property does not affect it.

Can Java HttpClient use a SOCKS5 proxy?

No, it supports HTTP proxies only. Use HttpURLConnection with Proxy.Type.SOCKS and a default Authenticator, or OkHttp with a SOCKS proxy.

Get your token and run the first Java request

Create an account, top up from $40 with crypto, and copy the gateway, username and token from the dashboard.