以下是一个简单的示例,展示如何通过设置系统属性来使用代理服务器进行HTTP连接。假设代理服务器的地址是proxy.example.com
,端口是8080
。
这次使用的是java.net
包设置代理,针对HTT 连接。
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Authenticator;
import java.net.InetSocketAddress;
import java.net.PasswordAuthentication;
import java.net.Proxy;
import java.net.URL;
import java.net.URLConnection;
public class ProxyExample {
public static void main(String[] args) {
// 设置代理服务器的地址和端口
System.setProperty("http.proxyHost", "proxy.example.com");
System.setProperty("http.proxyPort", "8080");
try {
// 创建URL对象
URL url = new URL("http://www.example.com");
// 打开连接
URLConnection connection = url.openConnection();
// 读取数据
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
while ((line = reader.readLine())!= null) {
System.out.println(line);
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
通过System.setProperty方法设置了http.proxyHost和http.proxyPort系统属性,分别指定了代理服务器的主机名和端口号。然后创建了一个URL对象,并通过openConnection方法打开连接。当进行连接时,会自动使用设置的代理服务器。最后读取连接返回的数据并打印。
如果代理服务器需要认证当代理服务器需要用户名和密码进行认证时,可以使用Authenticator类来设置认证信息。以下是一个示例:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Authenticator;
import java.net.InetSocketAddress;
import java.net.PasswordAuthentication;
import java.net.Proxy;
import java.net.URL;
import java.net.URLConnection;
public class ProxyAuthExample {
public static void main(String[] args) {
// 设置代理服务器的地址和端口
System.setProperty("http.proxyHost", "proxy.example.com");
System.setProperty("http.proxyPort", "8080");
// 设置代理认证信息
Authenticator.setDefault(new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("username", "password".toCharArray());
}
});
try {
// 创建URL对象
URL url = new URL("http://www.example.com");
// 打开连接
URLConnection connection = url.openConnection();
// 读取数据
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
while ((line = reader.readLine())!= null) {
System.out.println(line);
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
首先同样设置了代理服务器的主机和端口。然后通过Authenticator.setDefault
方法设置了一个自定义的Authenticator
。在getPasswordAuthentication
方法中返回了包含用户名和密码的PasswordAuthentication
对象。这样,在使用代理进行连接时,如果需要认证,就会使用提供的用户名和密码进行认证。
依照这个方法,大家可以试试看,欢迎交流讨论,感谢审核大大!