Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
249 views
in Technique[技术] by (71.8m points)

java - Take body of a post http request

Given for example this Post request:

    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":"[email protected]","password":"test123","foto":"myphoto.jpg","partecipanti":[]}

I want to take just the body of this request which in this case is a json. I'm my java code I can read all the request in this way:

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

But i'm not able to take just the body. Can someone help me to do this?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The headers are terminated by an empty line. You can consider only lines after the first empty one. This is valid only if the answer doesn't implement chuncked, gzip etc. as Stefan commented, but this can be ensured by the correct headers in http request. The use of a Client library is a valid alternative. HttpClient is part of Java since version 11.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...