2013-03-30 48 views
0

我正在尝试读取请求InputStream,但已到达流的末尾。HttpServletRequest InputStream读取返回-1

中唯一的类(的servlet)为:


    public class TestServlet extends HttpServlet 
    { 
     protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
     { 
      InputStream clientIn = request.getInputStream(); 
      OutputStream clientOut = response.getOutputStream(); 
      byte[] buffer = new byte[4096]; 
      int n; 
      try 
      { 
       while ((n = clientIn.read(buffer)) != -1) // ---------> Here, n is -1 
       { 
        System.out.println(new String(buffer,0,n)); 
        clientOut.write(("Ok = " + n).getBytes()); 
       } 
      } 
      catch (Exception e) 
      { 
       System.err.println(e); 
      } 
     } 
    } 

没有任何其他类(如过滤器,听众或其他的servlet)

和客户端的代码是:

 
    public class Main 
    { 
     public static void main(String[] args) throws IOException, InterruptedException 
     { 
      String postCommand = "POST/HTTP/1.1\r\n" + 
        "Host: localhost\r\n" + 
        "Content-Type: binary/octet-stream\r\n" + 
        "Connection: keep-alive\r\n\r\n" + 
        "name1=value1&name2=value2"; 

      Socket socket = new Socket("localhost", 8080); 
      InputStream serverIn = socket.getInputStream(); 
      OutputStream serverOut = socket.getOutputStream(); 
      serverOut.write(postCommand.getBytes()); 
      int n = 0, count = 1; 
      byte[] buffer = new byte[4096]; 
      do 
      { 
       if (n != 0) 
        System.out.println(new String(buffer, 0, n)); 
       serverOut.write(("foo " + count).getBytes()); 
      } while ((n = serverIn.read(buffer)) != -1 && count++

预先感谢您。亲切的问候!

+1

http包含数据时,http通常具有内容长度标题。 – jtahlborn

+0

您不能通过HTTP发送任意数据,您必须遵守[HTTP协议](http://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol)。你可以使用原始套接字来做你想做的事情,但是你不能使用HTTP servlet。您需要使用['HTTPUrlConnection'](http://docs.oracle.com/javase/tutorial/networking/urls/readingWriting.html)。 –

+0

@ bmorris591 - 建议*使用HTTPUrlConnection(或Apache HttpClient,或其他),但您不必*执行此操作。 –

回答

0

您的客户端未发送有效的HTTP 1.1。没有内容长度的标题,因此Servlet无法知道何时停止阅读。没有流的实际结束,因为HTTP客户端必须保持连接打开才能读取响应。

使用HttpURLConnection。