简体   繁体   中英

HttpServletRequest InputStream read return -1

I am trying to read a request InputStream but the end of the stream has been reached.

The only class (servlet) is:


    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);
            }
        }
    }

there is no any other classes (such as filter, listener or other servlet)

and the client code is:

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++

Thank you in advance. Kind regards!

Your client isn't sending valid HTTP 1.1. There is no content-length header and therefore no way for the Servlet to know when to stop reading. There is no actual end of stream because an HTTP client must keep the connection open to read the response.

Use an HttpURLConnection.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM