Search code examples
javahttpsshhttpsjsch

HTTPS tunnel inside SSH using JSch


I'd like to communicate with HTTPS server via SSH using Java library JSch. Streamforwarding example on library website is easy to use, even on SO is code with that (Java JSch create channel to access remote server via HTTP(s)).

Problem is when I want use HttpsURLConnection class to communicate via HTTPS. For instance to make GET request I try to operate on InputStream from Channel class (from JSch) and InputStream from HttpsUrlConnection.


Solution

  • Forward a local port via the SSH connection to the remote HTTP server port:

    Session session = jsch.getSession("username", "ssh.example.com");
    // ...
    session.connect();
    
    int forwardedPort = session.setPortForwardingL(0, "http.example.com", 80); 
    

    Now you can connect HttpsUrlConnection to http.example.com and port forwardedPort.