我在Amazon EC2上启动了一台机器,并且只向世界开放了端口22(因此只允许通过SSH连接到该机器)。我使用以下方法创建了一台到机器的隧道:
/usr/bin/ssh -C -N -D '*:20022' -i <ssh_key_file> -o ServerAliveInterval=20 -o ServerAliveCountMax=3 -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null ec2-user@ec2-a-b-c-d.compute-1.amazonaws.com
请注意,以上是公共DNS。
隧道工作正常,因为我在运行curl命令时输出正确:
curl --proxy socks5h://127.0.0.1:20022 https://ec2-a-b-c-d.compute-1.amazonaws.com:<my_port>
但是,我无法使用相同的SOCKS代理使用Java和HTTPURLConnection建立连接。这是一段代码:
import sun.net.www.protocol.http.HttpURLConnection;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.URL;
public static void main(String[] args) throws Exception {
String urlString = "http://ec2-a-b-c-d.compute-1.amazonaws.com:<my_port>";
URL url = new URL(urlString);
Proxy proxy = new Proxy(Proxy.Type.SOCKS, InetSocketAddress.createUnresolved("127.0.0.1", 20022));
System.out.println("Opening connection: " + url.toString() + " with proxy: " + proxy);
HttpURLConnection conn = (HttpURLConnection) url.openConnection(proxy);
conn.connect();
return 0;
}
它在&#34; conn.connect()&#34;以及以下堆栈跟踪超时; (行号不准确)
Exception in thread "main" java.net.SocketException: Malformed reply from SOCKS server
at java.net.SocksSocketImpl.readSocksReply(SocksSocketImpl.java:129)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:502)
at java.net.Socket.connect(Socket.java:579)
at java.net.Socket.connect(Socket.java:528)
at sun.net.NetworkClient.doConnect(NetworkClient.java:180)
at sun.net.www.http.HttpClient.openServer(HttpClient.java:432)
at sun.net.www.http.HttpClient.openServer(HttpClient.java:527)
at sun.net.www.http.HttpClient.<init>(HttpClient.java:211)
at sun.net.www.http.HttpClient.New(HttpClient.java:308)
at sun.net.www.http.HttpClient.New(HttpClient.java:326)
at sun.net.www.protocol.http.HttpURLConnection.getNewHttpClient(HttpURLConnection.java:997)
at sun.net.www.protocol.http.HttpURLConnection.plainConnect(HttpURLConnection.java:976)
at sun.net.www.protocol.http.HttpURLConnection.connect(HttpURLConnection.java:851)
at com.rajat.http_connection.HttpConnection.run(HttpConnection.java:53)
知道为什么会这样吗?