Matticus
Matticus

Reputation: 155

Java sockets closing HTTP 1.0 connections

I'm writing a small web server, and having a problem with parsing a request. I parse a BufferedReader into a LinkedList (so that I can perform operation based on POST data sent.) I found this answer explaining that the buffer isn't terminated due to the connection hanging open. I'm not sure how to close it.

How I open the socket (and how I thought to close it):

            Socket connectionSocket = serverSocket.accept();
            InetAddress client = connectionSocket.getInetAddress();

            System.out.println(client.getHostName() + " connected to server.");

            BufferedReader input = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream(), "UTF-8"));

            DataOutputStream output = new DataOutputStream(connectionSocket.getOutputStream());

            output.writeUTF(httpHeader(200));

            httpHandler(input, output);

            connectionSocket.close();

The httpHeader method forms a simple string with "HTTP/1.0" on the first line, and in this case, "200 OK" on the next line and a new line at the end. The POST request that is sent is HTTP 1.0.

Being as concise as I could manage, my question is two-fold: How do I properly respond to and close a HTTP 1.0 POST request/socket?

Upvotes: 0

Views: 437

Answers (1)

fge
fge

Reputation: 121830

A POST request has associated data, and MUST be accompanied by a Content-Length header specifying the exact length of that POST data.

So, you must first real all HTTP headers, decode the Content-Length, and then read the POST data (which is, as is classical with HTTP, separated from the headers by an empty line).

If the amount of data is not sufficient, or there is too much of it, or you don't even receive a Content-Length header, then you should return 400.

Upvotes: 1

Related Questions