Java 不通过代理链的代理发送数据包。因此,您必须在编码中设置代理。例如,当使用 HtmlUnit & WebClient 对象请求网页时,只需使用以下内容:
**WebClient webclient;**
if (proxy != null && !proxy.getHost().trim().equalsIgnoreCase("")) {
if (proxy.getType() == null || proxy.getType().trim().equalsIgnoreCase("")
|| proxy.getType().trim().equalsIgnoreCase("http") ||
proxy.getType().trim().equalsIgnoreCase("https"))
webclient = new WebClient(BrowserVersion.CHROME, proxy.getHost(), proxy.getPort());
else if (proxy.getType().trim().equalsIgnoreCase("socks")) {
System.setProperty("socksProxyHost", proxy.getHost());
System.setProperty("socksProxyPort", String.valueOf(proxy.getPort()));
webclient = new WebClient(BrowserVersion.CHROME);
}
webclient.getCredentialsProvider().setCredentials(AuthScope.ANY, new NTCredentials(
proxy.getUsername(), proxy.getPassword(), "", ""));
} else {
webclient = new WebClient(BrowserVersion.CHROME);
}
proxy 对象是下面定义的 Proxy 类的一个实例:
public class Proxy {
private String host, username, password,type;
private int port;
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public Proxy(String host, int port, String username, String password) {
this.host = host;
this.port = port;
this.username = username;
this.password = password;
}
public void setHost(String host) {
this.host = host;
}
public String getHost() {
return this.host;
}
public void setUsername(String username) {
this.username = username;
}
public String getUsername() {
return this.username;
}
public void setPassword(String password) {
this.password = password;
}
public String getPassword() {
return this.password;
}
public void setPort(int port) {
this.port = port;
}
public int getPort() {
return this.port;
}
}