# Java

Source: https://prontaro.com/docs/languages/java/

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

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](https://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 addresses Proxy credentials [Open in dashboard](https://my.prontaro.com/ips)

Export the proxy string to `PRONTARO_PROXY_URL`:

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

> **Why port :8080 for java.net.http.HttpClient and OkHttp**
>
> JDK’s `ProxySelector` and `java.net.Proxy.Type.HTTP` do not wrap the proxy hop itself in TLS — pointing them at `:443` fails because the Prontaro node expects a TLS ClientHello.
>
> Port `:8080` exists specifically for these clients: target HTTPS traffic inside the `CONNECT` tunnel remains end-to-end TLS. If you also require TLS to the proxy hop (`https://...:443`), use Apache HttpClient 5 or a [Relay URL](https://prontaro.com/docs/languages/java.md#calling-an-api-through-a-relay-url).

## `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=""
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](https://prontaro.com/docs/billing/limits.md).

## 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](https://my.prontaro.com/ips)), 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](https://prontaro.com/docs/outbound/relay.md) for TLS termination details and limits.

## Next steps

- [curl and environment variables](https://prontaro.com/docs/languages/curl.md) — diagnose `407` and `403` errors with `curl -v`.
- [HTTP & SOCKS5 proxy](https://prontaro.com/docs/outbound/proxy.md) — configure `access`, `targets`, and credential rotation.
- [Local port forwarding (prontaro forward)](https://prontaro.com/docs/outbound/forward.md) — route JDBC database connections through your static IP.
