# Use a proxy with Java HttpClient

Complete HTTPS requests using the JDK HttpClient, ProxySelector, proxy authentication, and timeout.

JDK 11 and later can use the standard library directly `java.net.http.HttpClient` There is no need to add third-party clients to the base HTTP proxy access.

## Precondition

- Running environment using JDK 11 or later.
- The account is closed. `us.zzhttp.com:7878`; Injection through controlled environment `PROXY_USERNAME` and `PROXY_PASSWORD`.
- The proxy password is only retained in the process environment or key service.

## Complete example

```java
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;
import java.util.Objects;

public final class ProxyExample {
    /**
     * Use JDK HttpClient to check the public exit IP through an authenticated proxy.
     */
    public static void main(String[] args) throws Exception {
        String proxyUsername = Objects.requireNonNull(System.getenv("PROXY_USERNAME"), "Missing proxy username");
        char[] proxyPassword = Objects.requireNonNull(System.getenv("PROXY_PASSWORD"), "Missing proxy password").toCharArray();

        HttpClient client = HttpClient.newBuilder()
            .connectTimeout(Duration.ofSeconds(10))
            .proxy(ProxySelector.of(new InetSocketAddress("us.zzhttp.com", 7878)))
            .authenticator(new Authenticator() {
                /** Send credentials only to the proxy and never to the destination server. */
                @Override
                protected PasswordAuthentication getPasswordAuthentication() {
                    if (getRequestorType() != RequestorType.PROXY) return null;
                    return new PasswordAuthentication(proxyUsername, proxyPassword);
                }
            })
            .build();

        HttpRequest request = HttpRequest.newBuilder()
            .uri(URI.create("https://ipinfo.io/json"))
            .timeout(Duration.ofSeconds(30))
            .GET()
            .build();
        HttpResponse<String> response = client.send(
            request,
            HttpResponse.BodyHandlers.ofString()
        );

        if (response.statusCode() >= 400) {
            throw new IllegalStateException("HTTP " + response.statusCode());
        }
        System.out.println(response.body());
    }
}
```

## Expected results

- The client first connects to the proxy and then tunnels to the HTTPS target.
- The response body shows the proxy export with a status code less than 400.
- Long life cycle services should be reused `HttpClient` The proceeds of the connection pool are retained.

## Error handling

- 407 Indicates that the proxy authentication failed, and that the username, password, and permissions are being checked.
- `HttpConnectTimeoutException` Indicates that the connection phase is longer than 10 seconds.
- The target status code and the proxy connection exception must be recorded separately.

## Safety tips

Don't type it in manually `Proxy-Authorization` Do not output environment variables in the exception log. When the agent identity changes, a new client is created to avoid the old connection continuing to carry the original authentication status.

html pre.shiki code .szBVR, html code.shiki .szBVR{--shiki-default:#D73A49;--shiki-dark:#F97583}html pre.shiki code .sVt8B, html code.shiki .sVt8B{--shiki-default:#24292E;--shiki-dark:#E1E4E8}html pre.shiki code .sScJk, html code.shiki .sScJk{--shiki-default:#6F42C1;--shiki-dark:#B392F0}html pre.shiki code .sJ8bj, html code.shiki .sJ8bj{--shiki-default:#6A737D;--shiki-dark:#6A737D}html pre.shiki code .s4XuR, html code.shiki .s4XuR{--shiki-default:#E36209;--shiki-dark:#FFAB70}html pre.shiki code .sZZnC, html code.shiki .sZZnC{--shiki-default:#032F62;--shiki-dark:#9ECBFF}html pre.shiki code .sj4cs, html code.shiki .sj4cs{--shiki-default:#005CC5;--shiki-dark:#79B8FF}html .default .shiki span {color: var(--shiki-default);background: var(--shiki-default-bg);font-style: var(--shiki-default-font-style);font-weight: var(--shiki-default-font-weight);text-decoration: var(--shiki-default-text-decoration);}html .shiki span {color: var(--shiki-default);background: var(--shiki-default-bg);font-style: var(--shiki-default-font-style);font-weight: var(--shiki-default-font-weight);text-decoration: var(--shiki-default-text-decoration);}html .dark .shiki span {color: var(--shiki-dark);background: var(--shiki-dark-bg);font-style: var(--shiki-dark-font-style);font-weight: var(--shiki-dark-font-weight);text-decoration: var(--shiki-dark-text-decoration);}html.dark .shiki span {color: var(--shiki-dark);background: var(--shiki-dark-bg);font-style: var(--shiki-dark-font-style);font-weight: var(--shiki-dark-font-weight);text-decoration: var(--shiki-dark-text-decoration);}
