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