Java 程序员同胞。我最近遇到了一个有趣的任务 - 创建将使用 SSH 隧道作为代理浏览网页(通过 HTTPS)的软件。在阅读了一些关于 JSCH 的文档(http://www.jcraft.com/jsch/,一个 Java SSH 隧道库)之后,这些文档都以数据库连接为例,我决定自己尝试一下。这是我从http://kahimyang.info/kauswagan/code-blogs/1337/ssh-tunneling-with-java-a-database-connection-example复制的连接代码
int assigned_port;
int local_port=3309;
// Remote host and port
int remote_port=3306;
String remote_host = "<SSH host goes here>";
String login = "<SSH login goes here>";
String password = "<SSH password goes here>";
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;
}
现在,我对所有端口转发的东西并不完全有经验,但是,如果我理解正确,代码应该通过 SSH 服务器转发所有传入 127.0.0.1:3309 (或任何分配的端口)的连接。现在我被困住了。我应该如何通过 127.0.0.1:3309 发送 HttpsURLConnection?我尝试将其定义为 HTTP 或 HTTPS 或 SOCKS 代理,但都不起作用。有谁能够帮我?