这个示例基于 demo-sdk-dedicated-proxy 的 Java 目录整理,适合已经使用 OkHttp 或需要 Java 最小可运行示例的场景。
运行前准备
- 设置环境变量:
PRIVATE_HOSTPRIVATE_PORTPRIVATE_USERNAMEPRIVATE_PASSWORD- 可选:
PRIVATE_BASE - 可选:
TARGET_URL
- 使用 Maven 构建,并确保依赖中包含
okhttp
示例代码
import okhttp3.Credentials;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Proxy;
public class Main {
private static String getenv(String key, String fallback) {
String value = System.getenv(key);
return (value != null && !value.isBlank()) ? value : fallback;
}
public static void main(String[] args) throws IOException {
String host = getenv("PRIVATE_HOST", "s1.ip.16yun.cn");
int port = Integer.parseInt(getenv("PRIVATE_PORT", "39010"));
String user = getenv("PRIVATE_USERNAME", getenv("PRIVATE_USER", null));
String pass = getenv("PRIVATE_PASSWORD", getenv("PRIVATE_PASS", null));
String target = getenv("TARGET_URL", "https://httpbin.org/ip");
String base = getenv("PRIVATE_BASE", "http://s1.ip.16yun.cn:887").replaceAll("/+$", "");
if (user == null || pass == null) {
throw new IllegalArgumentException("Missing PRIVATE_USERNAME/PRIVATE_PASSWORD");
}
OkHttpClient http = new OkHttpClient();
for (String path : new String[]{"current-ip", "switch-ip", "update"}) {
String url = String.format("%s/simple/%s?username=%s&password=%s", base, path, user, pass);
try (Response resp = http.newCall(new Request.Builder().url(url).build()).execute()) {
System.out.println(path + " " + resp.code());
System.out.println(resp.body() != null ? resp.body().string() : "");
}
}
Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(host, port));
OkHttpClient client = new OkHttpClient.Builder()
.proxy(proxy)
.proxyAuthenticator((route, response) ->
response.request().newBuilder()
.header("Proxy-Authorization", Credentials.basic(user, pass))
.build())
.build();
try (Response resp = client.newCall(new Request.Builder().url(target).build()).execute()) {
System.out.println(resp.code());
System.out.println(resp.body() != null ? resp.body().string() : "");
}
}
}
适合什么情况
- 你已经在 Java 服务中使用 OkHttp
- 你要同时验证管理接口和代理访问
- 你需要先确认 Java 里的代理认证写法