Skip to content
Sections

Java

Configure Java 11+ services to exit through your dedicated static IPv4 using HttpClient, OkHttp, or Spring RestClient — including the JVM proxy auth flag.

On this page9

Most Java HTTP clients open HTTP CONNECT tunnels over http:// on port :8080, while keeping target HTTPS traffic inside the tunnel end-to-end encrypted:

Client Proxy scheme Needs -Djdk.http.auth... flag
java.net.http.HttpClient http:// (:8080) Yes, required
OkHttp http:// (:8080) No
Spring RestClient (JdkClientHttpRequestFactory) http:// (:8080) Yes (when backed by JDK HttpClient)
Spring RestClient + Apache HttpClient 5 https:// (:443) or http:// (:8080) No

Step 1. Get your proxy URL

  1. Open IP addresses in your Prontaro dashboard (my.prontaro.com/ips) and select your IPv4.
  2. Under Proxy credentials, copy the HTTP (:8080) URL for JDK HttpClient / OkHttp, or the HTTPS (:443) URL if you use Apache HttpClient 5.
IP addressesProxy credentialsOpen in dashboard

Export the proxy string to PRONTARO_PROXY_URL:

bash
export PRONTARO_PROXY_URL="http://user:pass@<entry>.prontaro.io:8080"

java.net.http.HttpClient and the disabledSchemes trap

Why requests fail with 407 even when Authenticator is configured

By default, $JAVA_HOME/conf/net.properties sets jdk.http.auth.tunneling.disabledSchemes=Basic. Because of this, java.net.http.HttpClient refuses to send Proxy-Authorization: Basic on CONNECT tunnels and never invokes your Authenticator, throwing:

text
java.io.IOException: Unable to tunnel through proxy. Proxy returns "HTTP/1.1 407 Proxy Authentication Required"

Re-enable Basic proxy tunneling by passing the JVM flag at startup:

bash
java -Djdk.http.auth.tunneling.disabledSchemes="" CheckEgress.java

In Docker or Kubernetes, set JAVA_TOOL_OPTIONS="-Djdk.http.auth.tunneling.disabledSchemes=".

Do not rely on calling System.setProperty(...) inside main(): HttpClient reads this property once during class initialization, so if any framework class touches HttpClient earlier, System.setProperty is silently ignored.

Complete HttpClient + Authenticator example

Always check getRequestorType() == RequestorType.PROXY so proxy credentials are never sent to an upstream API that returns 401 Unauthorized:

java
// CheckEgress.java
import java.net.Authenticator;
import java.net.InetSocketAddress;
import java.net.PasswordAuthentication;
import java.net.ProxySelector;
import java.net.URI;
import java.net.URLDecoder;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.time.Duration;

public class CheckEgress {
    static HttpClient newProxyClient(String rawProxyUrl) {
        if (rawProxyUrl == null || rawProxyUrl.isBlank()) {
            throw new IllegalStateException("PRONTARO_PROXY_URL is not set");
        }
        URI proxy = URI.create(rawProxyUrl);
        String rawUserInfo = proxy.getRawUserInfo();
        if (rawUserInfo == null || !rawUserInfo.contains(":")) {
            throw new IllegalArgumentException("PRONTARO_PROXY_URL must contain user:pass");
        }
        String[] parts = rawUserInfo.split(":", 2);
        String user = URLDecoder.decode(parts[0], StandardCharsets.UTF_8);
        String pass = URLDecoder.decode(parts[1], StandardCharsets.UTF_8);
        int port = proxy.getPort() != -1 ? proxy.getPort() : 8080;

        return HttpClient.newBuilder()
            .connectTimeout(Duration.ofSeconds(5))
            .proxy(ProxySelector.of(new InetSocketAddress(proxy.getHost(), port)))
            .authenticator(new Authenticator() {
                @Override
                protected PasswordAuthentication getPasswordAuthentication() {
                    if (getRequestorType() != RequestorType.PROXY) {
                        return null;
                    }
                    return new PasswordAuthentication(user, pass.toCharArray());
                }
            })
            .build();
    }

    public static void main(String[] args) throws Exception {
        HttpClient client = newProxyClient(System.getenv("PRONTARO_PROXY_URL"));
        HttpRequest req = HttpRequest.newBuilder(URI.create("https://api.ipify.org"))
            .timeout(Duration.ofSeconds(15))
            .GET()
            .build();

        HttpResponse<String> resp = client.send(req, HttpResponse.BodyHandlers.ofString());
        if (resp.statusCode() < 200 || resp.statusCode() >= 300) {
            throw new RuntimeException("HTTP " + resp.statusCode() + ": " + resp.body());
        }
        System.out.println(resp.body().trim());
    }
}

Verify your outbound IP:

java -Djdk.http.auth.tunneling.disabledSchemes="" CheckEgress.java
203.0.113.10

Once this returns your dedicated IPv4, you can restrict destinations in the dashboard (IP addresses → Proxy credentials → Access).

OkHttp

OkHttp handles Proxy-Authorization itself and does not need -Djdk.http.auth.tunneling.disabledSchemes="". Always stop retrying if Proxy-Authorization is already set so bad credentials do not loop infinitely:

java
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.URI;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import okhttp3.Credentials;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

URI proxyUri = URI.create(System.getenv("PRONTARO_PROXY_URL"));
String[] parts = proxyUri.getRawUserInfo().split(":", 2);
String user = URLDecoder.decode(parts[0], StandardCharsets.UTF_8);
String pass = URLDecoder.decode(parts[1], StandardCharsets.UTF_8);
int port = proxyUri.getPort() != -1 ? proxyUri.getPort() : 8080;

// Reuse a single OkHttpClient across your application
OkHttpClient client = new OkHttpClient.Builder()
    .connectTimeout(Duration.ofSeconds(5))
    .callTimeout(Duration.ofSeconds(15))
    .proxy(new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyUri.getHost(), port)))
    .proxyAuthenticator((route, response) -> {
        if (response.request().header("Proxy-Authorization") != null) {
            return null; // stop retrying on invalid credentials
        }
        return response.request().newBuilder()
            .header("Proxy-Authorization", Credentials.basic(user, pass))
            .build();
    })
    .build();

Request req = new Request.Builder().url("https://api.ipify.org").build();
try (Response resp = client.newCall(req).execute()) {
    if (!resp.isSuccessful() || resp.body() == null) {
        throw new RuntimeException("HTTP " + resp.code());
    }
    System.out.println(resp.body().string().trim());
}

Spring RestClient (Spring Boot 3.2+)

Wire your configured HttpClient into JdkClientHttpRequestFactory and expose a single reusable RestClient @Bean:

java
import java.net.http.HttpClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.JdkClientHttpRequestFactory;
import org.springframework.web.client.RestClient;

@Configuration
public class PartnerApiConfig {
    @Bean
    RestClient partnerRestClient(@Value("${PRONTARO_PROXY_URL}") String proxyUrl) {
        HttpClient jdkClient = CheckEgress.newProxyClient(proxyUrl);
        JdkClientHttpRequestFactory factory = new JdkClientHttpRequestFactory(jdkClient);
        factory.setReadTimeout(java.time.Duration.ofSeconds(15));

        return RestClient.builder()
            .requestFactory(factory)
            .baseUrl("https://api.example.com")
            .build();
    }
}

Remember to pass -Djdk.http.auth.tunneling.disabledSchemes="" to the JVM. If you want TLS to the proxy hop on :443 with no JVM flags, back RestClient with HttpComponentsClientHttpRequestFactory using Apache HttpClient 5.

Common Java issues

  • Missing -Djdk.http.auth.tunneling.disabledSchemes="" in containers. Works locally in an IDE run config, then fails with 407 Proxy Authentication Required in production when omitted from the Dockerfile.
  • Using port :443 with ProxySelector or OkHttp. Causes immediate connection reset on tunnel setup — use http://...:8080 for JDK HttpClient and OkHttp.
  • Authenticator without RequestorType.PROXY. Sends your Prontaro proxy password to any upstream API that responds with 401.
  • Creating a new HttpClient or OkHttpClient per request. Each instance spins up its own thread and socket pool and risks hitting per-IP concurrent connection limits.

Calling an API through a Relay URL

With a Relay URL you need no ProxySelector, no Authenticator, and no disabledSchemes JVM flag — create a Relay in the dashboard (IP addresses), and your service makes a plain HTTPS request on port :443:

java
RestClient relayClient = RestClient.builder()
    .baseUrl(System.getenv("PRONTARO_RELAY_URL"))
    .defaultHeader("Authorization", "Bearer " + System.getenv("PARTNER_API_TOKEN"))
    // Include only if you enabled a password (in the dashboard under IP addresses → Relay address → Access):
    .defaultHeader("Prontaro-Relay-Auth", System.getenv("RELAY_LOGIN") + ":" + System.getenv("RELAY_PASSWORD"))
    .build();

String body = relayClient.get()
    .uri("/v1/status")
    .retrieve()
    .body(String.class);

See Relay URLs for TLS termination details and limits.

Next steps

Something wrong on this page? Contact us

Contact us

Enter your email so we can reply.Enter a valid email, e.g. name@company.example.
Tell us what you need or what went wrong.up to 2,000 characters

Sent! We’ll reply to .

Or email us at support@prontaro.com