独享代理 Java 示例

阅读模式

这个示例基于 demo-sdk-dedicated-proxy 的 Java 目录整理,适合已经使用 OkHttp 或需要 Java 最小可运行示例的场景。

运行前准备

  • 设置环境变量:
    • PRIVATE_HOST
    • PRIVATE_PORT
    • PRIVATE_USERNAME
    • PRIVATE_PASSWORD
    • 可选:PRIVATE_BASE
    • 可选:TARGET_URL
  • 使用 Maven 构建,并确保依赖中包含 okhttp

示例代码

1
import okhttp3.Credentials;
2
import okhttp3.OkHttpClient;
3
import okhttp3.Request;
4
import okhttp3.Response;
5
6
import java.io.IOException;
7
import java.net.InetSocketAddress;
8
import java.net.Proxy;
9
10
public class Main {
11
private static String getenv(String key, String fallback) {
12
String value = System.getenv(key);
13
return (value != null && !value.isBlank()) ? value : fallback;
14
}
15
16
public static void main(String[] args) throws IOException {
17
String host = getenv("PRIVATE_HOST", "s1.ip.16yun.cn");
18
int port = Integer.parseInt(getenv("PRIVATE_PORT", "39010"));
19
String user = getenv("PRIVATE_USERNAME", getenv("PRIVATE_USER", null));
20
String pass = getenv("PRIVATE_PASSWORD", getenv("PRIVATE_PASS", null));
21
String target = getenv("TARGET_URL", "https://httpbin.org/ip");
22
String base = getenv("PRIVATE_BASE", "http://s1.ip.16yun.cn:887").replaceAll("/+$", "");
23
24
if (user == null || pass == null) {
25
throw new IllegalArgumentException("Missing PRIVATE_USERNAME/PRIVATE_PASSWORD");
26
}
27
28
OkHttpClient http = new OkHttpClient();
29
for (String path : new String[]{"current-ip", "switch-ip", "update"}) {
30
String url = String.format("%s/simple/%s?username=%s&password=%s", base, path, user, pass);
31
try (Response resp = http.newCall(new Request.Builder().url(url).build()).execute()) {
32
System.out.println(path + " " + resp.code());
33
System.out.println(resp.body() != null ? resp.body().string() : "");
34
}
35
}
36
37
Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(host, port));
38
OkHttpClient client = new OkHttpClient.Builder()
39
.proxy(proxy)
40
.proxyAuthenticator((route, response) ->
41
response.request().newBuilder()
42
.header("Proxy-Authorization", Credentials.basic(user, pass))
43
.build())
44
.build();
45
46
try (Response resp = client.newCall(new Request.Builder().url(target).build()).execute()) {
47
System.out.println(resp.code());
48
System.out.println(resp.body() != null ? resp.body().string() : "");
49
}
50
}
51
}

适合什么情况

  • 你已经在 Java 服务中使用 OkHttp
  • 你要同时验证管理接口和代理访问
  • 你需要先确认 Java 里的代理认证写法

相关入口