Java使用hutool调用Http代理IP的代码样例
站大爷
官方
2024-01-20
1801 浏览
温馨提示:
1. 此代码样例同时支持访问http和https网页
2. 使用用户名密码访问的情况下,每次请求会发送两次进行认证从而导致请求耗时增加,建议使用终端IP授权
3. 依赖包下载:
import java.net.Authenticator;
import java.net.PasswordAuthentication;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpRequest;
// 代理验证信息
class ProxyAuthenticator extends Authenticator {
private String user, password;
public ProxyAuthenticator(String user, String password) {
this.user = user;
this.password = password;
}
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(user, password.toCharArray());
}
}
public class TestProxyHutool {
// 用户名密码授权
final static String ProxyUser = "username";
final static String ProxyPass = "password";
// 代理IP、端口号
final static String ProxyHost = "159.138.141.125";
final static Integer ProxyPort =18916;
public static void main(String[] args) {
// 目标网站
String url = "https://example.com";
// JDK 8u111版本后,目标页面为HTTPS协议,启用proxy用户密码鉴权
System.setProperty("jdk.http.auth.tunneling.disabledSchemes", "");
// 设置请求验证信息
Authenticator.setDefault(new ProxyAuthenticator(ProxyUser, ProxyPass));
// 发送请求
HttpResponse result = HttpRequest.get(url)
.setHttpProxy(ProxyHost, ProxyPort)
.timeout(20000)//设置超时,毫秒
.execute();
System.out.println(result.body());
}
}