title: Java - connect to webpage using SSH tunneling
body: <p>fellow Java coders. I have recently been faced with an interesting task - to create software that would use an SSH tunnel as a proxy for browsing webpages (over HTTPS). After reading some docs on JSCH (<a href="http://www.jcraft.com/jsch/" rel="nofollow">http://www.jcraft.com/jsch/</a>, a Java SSH tunneling library), which all gave database connections as an example, I decided to try it myself. Here is the connection code I copied from <a href="http://kahimyang.info/kauswagan/code-blogs/1337/ssh-tunneling-with-java-a-database-connection-example" rel="nofollow">http://kahimyang.info/kauswagan/code-blogs/1337/ssh-tunneling-with-java-a-database-connection-example</a></p>
  
  <pre><code>int assigned_port;   
      int local_port=3309;
  
      // Remote host and port
      int remote_port=3306;
      String remote_host = "&lt;SSH host goes here&gt;";
      String login = "&lt;SSH login goes here&gt;";
      String password = "&lt;SSH password goes here&gt;";
  
      try {
          JSch jsch = new JSch(); 
  
          // Create SSH session.  Port 22 is your SSH port which
          // is open in your firewall setup.
          Session session = jsch.getSession(login, remote_host, 22);
          session.setPassword(password);
  
          // Additional SSH options.  See your ssh_config manual for
          // more options.  Set options according to your requirements.
          java.util.Properties config = new java.util.Properties();
          config.put("StrictHostKeyChecking", "no");
          config.put("Compression", "yes");
          config.put("ConnectionAttempts","2");
  
          session.setConfig(config);
  
          // Connect
          session.connect();            
  
          // Create the tunnel through port forwarding.  
          // This is basically instructing jsch session to send 
          // data received from local_port in the local machine to 
          // remote_port of the remote_host
          // assigned_port is the port assigned by jsch for use,
          // it may not always be the same as
          // local_port.
  
          assigned_port = session.setPortForwardingL(local_port, 
                  remote_host, remote_port);
  
      } catch (JSchException e) {            
          System.out.println("JSch:" + e.getMessage());
          return;
      }
  
      if (assigned_port == 0) {
          System.out.println("Port forwarding failed!"); 
          return;
      }
  </code></pre>
  
  <p>Now, I am not exactly experienced with all the port forwarding stuff, but, if I understand it correctly, the code is supposed to forward all connections incoming to 127.0.0.1:3309 (or whatever the assigned_port is) through the SSH server. Now I'm stuck. How am I supposed to send a HttpsURLConnection through 127.0.0.1:3309? I tried defining it as an HTTP or HTTPS or SOCKS proxy, but neither works. Can anybody help me?</p>