Java での接続
割り当て済みの静的エンドポイントから通信します。環境変数で認証情報を読み込み、既定では HTTP プロキシサーバー経由で HTTPS にアクセスします。IP の取得や切り替え処理は含みません。
接続前の準備
実行するターミナル・コンテナー・配備先で PROXY_HOST、PROXY_PORT、PROXY_USERNAME、PROXY_PASSWORD を設定します。管理画面の現在の情報と対応ポートを使い、実際のパスワードをリポジトリー、ログ、フロントエンドへ含めないでください。
実行環境と依存関係
JDK 11 以降の Maven プロジェクトへ以下の依存関係を追加します。src/main/java/ProxyExample.java に保存し、IDE の main または Maven Exec プラグインで実行します。HTTP ポートで認証し、HTTPS は CONNECT トンネルで転送します。
xml
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>4.12.0</version>
</dependency>設定手順
java
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.time.Duration;
import okhttp3.Credentials;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
public final class ProxyExample {
private static String required(String name) {
String value = System.getenv(name);
if (value == null || value.isBlank()) {
throw new IllegalArgumentException("Missing environment variable: " + name);
}
return value;
}
public static void main(String[] args) {
String host = required("PROXY_HOST").replace("[", "").replace("]", "");
int port = Integer.parseInt(required("PROXY_PORT"));
String credential = Credentials.basic(required("PROXY_USERNAME"), required("PROXY_PASSWORD"));
OkHttpClient client = new OkHttpClient.Builder()
.proxy(new Proxy(Proxy.Type.HTTP, new InetSocketAddress(host, port)))
.proxyAuthenticator((route, response) -> {
if (response.request().header("Proxy-Authorization") != null) return null;
return response.request().newBuilder()
.header("Proxy-Authorization", credential).build();
})
.connectTimeout(Duration.ofSeconds(10))
.readTimeout(Duration.ofSeconds(30))
.callTimeout(Duration.ofSeconds(40))
.build();
Request request = new Request.Builder().url("https://ip123.in/ip.json").build();
try (Response response = client.newCall(request).execute()) {
if (!response.isSuccessful()) {
System.err.println("HTTP status: " + response.code());
System.exit(1);
}
if (response.body() != null) System.out.println(response.body().string());
} catch (java.io.IOException error) {
System.err.println("Proxy request failed; check network and credentials");
System.exit(1);
}
}
}この例は HTTP 接続用です。SOCKS5 のユーザー名・パスワード認証には対応実装が必要です。Proxy.Type.HTTP を SOCKS に変えるだけでは HTTP 用の認証処理は引き継がれません。
うまく接続できない場合
例だけ成功する場合は、実際の通信プロセス、SDK の設定、タイムアウト、再試行を確認します。TLS 証明書の検証は有効なままにしてください。例は認証情報を含むエラーを出力しません。調査ログも伏せ字にします。よくある質問を参照してください。