将 HtmlUnit 的代理凭据限定到代理主机
配置 HtmlUnit 代理,并使用凭据提供程序的主机/端口作用域,同时为 NTLM 指定 domain 和 workstation 字段。
HtmlUnit 的代理配置用于选定中间代理,而其凭据提供程序负责为该主机和端口提供账号。对于 NTLM 代理,HtmlUnit 4.21.0 的 API 提供了专用方法:
String proxyHost = "proxy.example";
int proxyPort = 8080;
DefaultCredentialsProvider credentials = new DefaultCredentialsProvider();
credentials.addNTLMCredentials(
user, password.toCharArray(), proxyHost, proxyPort, workstation, domain);
try (WebClient browser = new WebClient()) {
browser.getOptions().setProxyConfig(
new ProxyConfig(proxyHost, proxyPort, "http"));
browser.setCredentialsProvider(credentials);
HtmlPage page = browser.getPage("https://www.example.com/");
}
这些类使用当前的 org.htmlunit 包,HtmlPage 位于 org.htmlunit.html 中。请按实际环境填写代理账号的 workstation 和 domain;目标网站并不是 NTLM 的 domain 字段。
若要登记通用的用户名/密码凭据,同一个提供程序还提供 addCredentials,参数为 username、char 数组密码、host、port 与 realm。realm 传 null 表示作用于该限定端点上的任意 realm。
请选用与代理认证方案以及实际部署的依赖相匹配的重载。旧版 HtmlUnit 2.x 示例使用不同的包名,密码参数也可能是字符串;上面的代码用的是 4.21.0 的 API。