BufferedReader not reading past empty line [closed

2019-07-04 12:37发布

问题:

I'm trying to figure out why my BufferedReader (reading from an InputStream) just hangs and doesn't read after an empty line is received.

Trying to read in a POST request that looks something like:

POST /test.php HTTP/1.0
Content-Length: 30
Content-Type: text/html;

postData=whatever&moreData...

I know the post data is being sent correctly (in the above format), however I'm unable to retrieve the posted data. I would expect the following code to print out the post data then hang waiting for more.. but, what actually happens is it hangs after the "Content-Type" line.

while (true) {
    System.out.println(bufferedReader.readLine());
}

Code used to obtain stream:

bufferedReader = new BufferedReader(clientSocket.getInputStream());

Does anyone know why this is happening?

Thanks

回答1:

The POST method will not add a newline character at the end. What you need to do is get the Content-Length and after the last empty line read that many characters.

Example

Let's assume we have a following HTML page:

<html>
<head/>
<body>
    <form action="http://localhost:12345/test.php" method="POST">
        <input type="hidden" name="postData" value="whatever"/>
        <input type="hidden" name="postData2" value="whatever"/>
        <input type="submit" value="Go"/>
    </form>
</body>
</html>

Now we start a very simple server which somehow resembles your code (this code is full of wholes, but that's not the issue):

public class Main {
    public static void main(final String[] args) throws Exception {
        final ServerSocket serverSocket = new ServerSocket(12345);
        final Socket clientSocket = serverSocket.accept();
        final InputStreamReader reader = new InputStreamReader(clientSocket.getInputStream());
        final BufferedReader bufferedReader = new BufferedReader(reader);
        int contentLength = -1;
        while (true) {
            final String line = bufferedReader.readLine();
            System.out.println(line);

            final String contentLengthStr = "Content-Length: ";
            if (line.startsWith(contentLengthStr)) {
                contentLength = Integer.parseInt(line.substring(contentLengthStr.length()));
            }

            if (line.length() == 0) {
                break;
            }
        }

        // We should actually use InputStream here, but let's assume bytes map
        // to characters
        final char[] content = new char[contentLength];
        bufferedReader.read(content);
        System.out.println(new String(content));
    }
}

When we load the page in our favorite browser and press the Go button, we should some the content of the POST body in the console.