简体   繁体   English

获取 POST 请求的正文 [Java]

[英]Get body of POST request [Java]

I'm trying to write a simple HTTP server but can't figure out how to read the body segment of a POST-request.我正在尝试编写一个简单的 HTTP 服务器,但无法弄清楚如何读取 POST 请求的正文部分。 I'm having trouble reading beyond the empty line after the headers.我在阅读标题后的空行时遇到问题。

Here's what I do:这就是我所做的:

    BufferedReader br = new BufferedReader(new InputStreamReader(client.getInputStream()));
    StringBuilder request = new StringBuilder();
    String line;
    while(!(line = br.readLine()).isEmpty()) {
        request.append(line).append(CRLF);
        System.out.println(line);
    }
    
    // read body ?

So this basically loads the Request and headers in a String.因此,这基本上将请求和标头加载到字符串中。 But I can't figure out how to skip that one line that separates the headers from the body.但我不知道如何跳过将标题与正文分开的那一行。

I've tried readLine(),= null or to manually read two more lines after the loop terminates.我试过 readLine(),= null 或在循环终止后手动读取两行。 but that results in a loop.但这会导致循环。

Try parsing the content-length header to get the number of bytes.尝试解析内容长度 header 以获取字节数。 After the blank line you'll want to read exactly that many bytes.在空白行之后,您将想要读取那么多字节。 Using readLine() won't work because the body isn't terminated by a CRLF.使用 readLine() 将不起作用,因为正文没有被 CRLF 终止。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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