为什么我的SOCKS代理代码会抛出SocketException: Malformed reply from SOCKS server
?我试图在URLConnection或其他设置,但这不起作用。唯一有用的东西 - chilkat lib,但它是商业的。那么,我如何通过ASOCKS代理发出http请求呢?也许存在一些免费的lib?
例如,该代码:
SocketAddress addr = new InetSocketAddress(proxy_ip, proxy_port);
Proxy proxy = new Proxy(Proxy.Type.SOCKS, addr);
Socket socket = new Socket(proxy);
InetSocketAddress dest = new InetSocketAddress("google.com", 80);
try {
socket.connect(dest);
} catch (IOException ex) {
Logger.getLogger(CheckProxy.class.getName()).log(Level.SEVERE, null, ex);
}
抛出异常:
java.net.SocketException: Malformed reply from SOCKS server
at java.net.SocksSocketImpl.readSocksReply(Unknown Source)
at java.net.SocksSocketImpl.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at proxychecker.CheckProxy.SocksCheck(CheckProxy.java:86)
第86行是“socket.connect(dest);”
答案 0 :(得分:4)
SocketException: Malformed reply from SOCKS server
这表明您根本没有SOCKS代理。可能是HTTP代理。
请注意,您提出了错误的问题。你的代码是正确的,这是你的错误。
答案 1 :(得分:3)
此错误的解释:bugs.java.com/view_bug.do?bug_id=6964547
您需要使用以下代码手动更改Socket对象中的模式:
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) {
}