我正在尝试读取请求InputStream
,但已到达流的末尾。
唯一的类(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++
提前谢谢你。亲切的问候!
答案 0 :(得分:1)
您的客户端未发送有效的HTTP 1.1。没有内容长度标头,因此Servlet无法知道何时停止读取。没有实际的流结束,因为HTTP客户端必须保持连接打开才能读取响应。
使用HttpURLConnection。