在复杂的网络环境中,很多使用socks5代理服务器,那么在代码中通常一些socket连接操作需要针对socks5协议做一些修改。下面我们主要介绍java中对于使用socks5代理的改造。
1.基于jsch进行ssh连接
public void connect() throws JSchException{
int i = 0;
for (; i < this.tryConnectTimes; i++) {
try {
this.session = jsch.getSession(this.user, this.host, this.port);
this.session.setConfig(this.properties);
this.session.setPassword(this.password);
this.session.setSocketFactory(this.socketFactory);
this.session.setTimeout(this.readTimeout);
//加上这段设置代理
ProxySOCKS5 proxy = new ProxySOCKS5("172.16.0.14", 1002);
proxy.setUserPasswd("dds", "ueJ20@d8in25");
session.setProxy(proxy);
this.session.connect();
if (this.session.isConnected()) {
logger.debug(this.host + " : " + this.port +" 连接成功, 用户 : " + this.user);
break;
}
} catch (JSchException e) {
logger.warn("第"+(i+1) + "次连接失败 " + this.host + " : " + this.port + ", 用户: " + this.user, e);
}
//sleep 后,尝试重新连接
if (i != tryConnectTimes - 1) {
try {
Thread.sleep(this.sleepTime);
} catch (InterruptedException e) {
logger.warn("connect() : sleep 出现异常");
}
}
}
//达到最大连接次数,抛出异常
if (i >= tryConnectTimes) {
throw new JSchException(this.host + " : " + this.port + " 连接超时, 用户: " + this.user);
}
}
2.Spring中RestTemplate通过socks5连接
public static RestTemplate createRestTemplateWithSocks5Proxy(String socks5Host, int socks5Port, String username, String password) {
// 创建 SOCKS5 代理的主机
HttpHost socks5Proxy = new HttpHost(socks5Host, socks5Port, "socks");
// 创建凭据提供程序,并设置凭据
CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password));
// 创建 HttpClient,并配置 SOCKS5 代理和凭据提供程序
CloseableHttpClient httpClient = HttpClients.custom()
.setDefaultCredentialsProvider(credentialsProvider)
.setRoutePlanner(new DefaultProxyRoutePlanner(socks5Proxy) {
@Override
public HttpHost determineProxy(org.apache.http.HttpHost target,
org.apache.http.HttpRequest request,
org.apache.http.protocol.HttpContext context) throws HttpException {
// 如果目标主机是需要走代理的,返回代理主机
if ("example.com".equals(target.getHostName())) {
return super.determineProxy(target, request, context);
}
// 否则返回 null,表示直接连接目标主机
return null;
}
})
.build();
// 创建 HttpComponentsClientHttpRequestFactory,并设置 HttpClient
HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(httpClient);
// 创建 RestTemplate,并设置请求工厂
RestTemplate restTemplate = new RestTemplate(requestFactory);
return restTemplate;
}