2013-03-30 52 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。