此示例是通过修改JVM中的网络设置来达到代理的效果,如果程序员有些请求不需要代理可以在代理请求之后再将JVM配置项改回默认项。支持http、https、socks5代理
此代码以http和https代理为例:
``
```java
// 使用socks5代理配置
package com.qg;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.*;
public class ProxyClient {
//用户key
private static String user = "key";
//用户密码
private static String password = "proxy_password";
//获取到的代理IP
private static String proxyIP = "127.0.0.1";
//获取到的代理端口
private static String proxyPort = "1080";
public static void main(String[] args) {
// 下面http、https代理和socks5代理只需要设置一个就可以
// 使用http代理和https代理
System.setProperty("http.proxySet", "true");
// 发起http请求时使用的代理服务器配置
System.setProperty("http.proxyHost", proxyIP);
System.setProperty("http.proxyPort", proxyPort);
// 发起https请求时使用的代理服务器配置
System.setProperty("https.proxyHost", proxyIP);
System.setProperty("https.proxyPort", proxyPort);
// 这行代码是身份验证的关键配置,不然身份验证不起作用
System.setProperty("jdk.http.auth.tunneling.disabledSchemes", "");
System.setProperty("jdk.http.auth.proxying.disabledSchemes", "");
// 身份验证
Authenticator.setDefault(
new Authenticator() {
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(
user, password.toCharArray());
}
}
);
sendRequest("http://httpbin.org/get");
sendRequest("https://httpbin.org/get");
}
public static void sendRequest(String urlStr) {
URL url;
&nbs; BufferedReader in;
StringBuilder result = new StringBuilder();
try {
url = new URL(urlStr);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.connect();
in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result.append(line);
}
conn.disconnect();
System.out.println("http status code:" conn.getResponseCode());
System.out.println("body: " result);
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
如需使用socks5代理可以将main函数中的代码替换为:
```java
// 使用socks5代理配置
System.setProperty("socksProxyHost", proxyIP);
System.setProperty("socksProxyPort", proxyPort);
System.setProperty("socksProxyVersion", "5");
System.setProperty("java.net.socks.username", user);
System.setProperty("java.net.socks.password", password);
```