title: HTTPURLConnection with SOCKS proxy
body: <p>I have launched a machine on Amazon EC2 and only have port 22 open to the world (so only SSH to the machine is allowed). I created a tunnel to the machine using:</p>
  
  <pre><code>/usr/bin/ssh -C -N -D '*:20022' -i &lt;ssh_key_file&gt; -o ServerAliveInterval=20 -o ServerAliveCountMax=3 -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null ec2-user@ec2-a-b-c-d.compute-1.amazonaws.com
  </code></pre>
  
  <p>Note that the above is a public DNS.</p>
  
  <p>The tunnel works fine, because I'm getting correct output when I run a curl command:</p>
  
  <pre><code>curl --proxy socks5h://127.0.0.1:20022 https://ec2-a-b-c-d.compute-1.amazonaws.com:&lt;my_port&gt;
  </code></pre>
  
  <p>However, I'm not able to establish connection using Java and HTTPURLConnection using the same SOCKS proxy. Here's the piece of code:</p>
  
  <pre><code>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:&lt;my_port&gt;";
  
    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;
  }
  </code></pre>
  
  <p>It times out with the following stack trace at "conn.connect()" (line numbers not accurate)</p>
  
  <pre><code>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.&lt;init&gt;(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)
  </code></pre>
  
  <p>Any idea why this is the case?</p>