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 代理 IP 配置、超时和重试策略。不要通过关闭 TLS 证书校验解决连接错误。示例只输出查询结果或不含凭据的错误;排查日志也应脱敏。详见常见问题。