使用 Socks 4 代理进行 HTTP 调用 [英] HTTP call with Socks 4 proxy
问题描述
我需要使用 socks 4 代理调用服务器.我使用的是 Java 1.6 版.
I need to call a server using a socks 4 proxy. I am on java version 1.6.
如果我们使用这样的东西,那么它会将 SOCKS 代理视为版本 5.
If we use something like this then it treats the SOCKS proxy as version 5.
URL url = new URL("https://www.google.com");
URLConnection connection = null;
SocketAddress proxySocketAddress1 = new InetSocketAddress("XXXXXXXXXX", 8081);
Proxy proxy = new Proxy(Proxy.Type.SOCKS, proxySocketAddress1);
connection = url.openConnection(proxy);
connection.setConnectTimeout(150000);
connection.connect();
我可以在系统级别设置socks代理
I can setup socks proxy at the system level by doing
// Set SOCKS proxy
System.getProperties().put( "socksProxyHost","xxxxx");
System.getProperties().put( "socksProxyPort","1234");
System.getProperties().put("socksProxyVersion","4");
当我这样做时,我能够访问服务器
When I do this I am able to reach the server
connection = url.openConnection();
但我的其他连接,如连接到数据库、加密服务器也通过代理并失败.
But my other connections like connections to db, encryption server also goes thru the proxy and fails.
我也尝试从系统代理中排除服务器,但没有成功.
I also tried excluding servers from system proxy but no success.
System.getProperties().put("socksnonProxyHosts","*.net");
System.getProperties().put("http.nonProxyHosts","*.net");
有没有其他方法可以选择在 java 1.6 中使用 SOCKS4.
Is there any other way I can choose to use SOCKS4 in java 1.6.
推荐答案
这是我尝试过的方法,看起来很有效.基本上我需要 SOCKS4 代理才能连接到套接字.
This is what I tried and seems like it's working. Basically I need SOCKS4 proxy to connect to a socket.
SocketAddress socketAddress = new InetSocketAddress("proxyhost",proxyport);
Proxy socketProxy = new Proxy(Proxy.Type.SOCKS, socketAddress);
Socket socket = new Socket(socketProxy);
Class clazzSocks = socket.getClass();
Method setSockVersion = null;
Field sockImplField = null;
SocketImpl socksimpl = null;
try {
sockImplField = clazzSocks.getDeclaredField("impl");
sockImplField.setAccessible(true);
socksimpl = (SocketImpl) sockImplField.get(socket);
Class clazzSocksImpl = socksimpl.getClass();
setSockVersion = clazzSocksImpl.getDeclaredMethod("setV4");
setSockVersion.setAccessible(true);
if(null != setSockVersion){
setSockVersion.invoke(socksimpl);
}
sockImplField.set(socket, socksimpl);
}
catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String hostName="xxxxx";
int port=1080;
InetAddress address;
SocketAddress socketAddress;
address = InetAddress.getByName(hostName);
socketAddress = new InetSocketAddress(address, port);
// Connect to socket
socket.connect(socketAddress, 100000);
//setting the socket read() connection time out
socket.setSoTimeout(100000);
请分享您对此方法的意见和反馈.
Please share your comments, feedback for this approach.
这篇关于使用 Socks 4 代理进行 HTTP 调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!