获取 body 个 post http 请求

Take body of a post http request

例如这个 Post 请求:

    Using port: 8080
    Using Webroot: /tmp
    POST /registrazione HTTP/1.1
    Content-Type: application/json
    User-Agent: PostmanRuntime/7.26.8
    Accept: */*
    Postman-Token: a628e69a-9ab1-4ef1-8b1d-7634e4dbbeab
    Host: 127.0.0.1:8080
    Accept-Encoding: gzip, deflate, br
    Connection: keep-alive
    Content-Length: 150

    {"id":0,"nome":"Rocco","cognome":"I nandu","username":"roccuzzu","email":"rock@gmail.com","password":"test123","foto":"myphoto.jpg","partecipanti":[]}

我只想获取此请求的 body,在本例中为 json。 我是我的 java 代码 我可以通过这种方式读取所有请求:

    BufferedReader in = null;
    String call = null;

    try {
        inputStream = socket.getInputStream();
        outputStream = socket.getOutputStream();
        in = new BufferedReader(new InputStreamReader(socket.getInputStream()));

        int bytes;
        while((bytes = in.read()) >=0){
            System.out.print((char) bytes);
        }

但我无法只接受 body。有人可以帮我做这个吗?

headers 以空行结束。您可以只考虑第一个空行之后的行。 只有当答案没有像 Stefan 评论的那样实现 chuncked、gzip 等时,这才有效,但这可以通过 http 请求中正确的 headers 来确保。 使用客户端库是一个有效的选择。自版本 11 以来,HttpClient 是 Java 的一部分。

我找到了一种方法。它不优雅但有效:

    private String parseBody() throws IOException {
    int bytes;
    int s = 0, e = 0;
    String request;
    StringBuilder sb = new StringBuilder();
    while((bytes = in.read()) >=0){
        if(bytes == '\r'){
            bytes = in.read();
            if(bytes == '\n'){
                bytes = in.read();
                if(bytes == '\r'){
                    bytes = in.read();
                    if(bytes == '\n'){
                        while((bytes = in.read()) >= 0){
                            sb.append((char)bytes);
                            if(bytes == '{'){
                                e = e + 1;
                            }
                            if(bytes == '}'){
                                s = s + 1;
                                if(s == e){
                                    request = sb.toString();
                                    return request;
                                }
                            }
                        }
                    }
                }
            }
        }
    }
    return null;
}

当然,我愿意接受任何改进和建议。