2013-03-04 95 views
0

我正在尝试使用JSCH连接到远程服务器,然后从该服务器通过tcp/ip端口打开一个类似于会话的telnet。假设连接到服务器A,并且一旦连接,就通过另一个端口向服务器B发出tcp连接。在我的网络服务器日志中,我看到一个GET /记录但不是我所期望的GET/foo。我在这里错过了什么? (我并不需要使用端口转发,因为远程端口是我连接到系统的访问)通过安全的ssh连接的TCP连接

package com.tekmor; 

import com.jcraft.jsch.*; 

import java.io.BufferedReader; 
. 
. 

public class Siranga { 

    public static void main(String[] args){ 
     Siranga t=new Siranga(); 
      try{ 
       t.go(); 
      } catch(Exception ex){ 
       ex.printStackTrace(); 
     } 
    } 
    public void go() throws Exception{ 
     String host="hostXXX.com"; 
     String user="USER"; 
     String password="PASS"; 
     int port=22; 

     Properties config = new Properties(); 
     config.put("StrictHostKeyChecking", "no");  

     String remoteHost="hostYYY.com"; 
     int remotePort=80; 


     try { 
     JSch jsch=new JSch(); 
     Session session=jsch.getSession(user, host, port); 
     session.setPassword(password); 
     session.setConfig(config); 
     session.connect(); 
     Channel channel=session.openChannel("direct-tcpip"); 


     ((ChannelDirectTCPIP)channel).setHost(remoteHost); 
     ((ChannelDirectTCPIP)channel).setPort(remotePort); 

     String cmd = "GET /foo"; 

     InputStream in = channel.getInputStream(); 
     OutputStream out = channel.getOutputStream(); 

     channel.connect(10000); 

     byte[] bytes = cmd.getBytes();   
     InputStream is = new ByteArrayInputStream(cmd.getBytes("UTF-8")); 

     int numRead; 

     while ((numRead = is.read(bytes)) >= 0) { 
       out.write(bytes, 0, numRead); 
       System.out.println(numRead); 
     } 

     out.flush(); 



     channel.disconnect(); 
     session.disconnect(); 

     System.out.println("foo"); 

     } 
     catch (Exception e){ 
      e.printStackTrace(); 

     } 

    } 
} 

回答

0

再次阅读您的HTTP specification。请求标题应该以空行结束。所以假设你没有更多的标题行,你至少得在最后换行。 (此处的换行符表示CRLF组合。)

此外,请求行应包含URL后面的HTTP版本标识符。

因此,尝试这种变化你的程序:

String command = "GET /foo HTTP/1.0\r\n\r\n"; 

作为一个提示:而不是从你ByteArrayInputStream的人工管道数据通道的输出流,你可以使用setInputStream method。另外,不要忘记从频道的输入流中读取结果。