简体   繁体   中英

Handling json post payload in java HttpServletRequest

I have a problem with post'ing json object to my java HttpServletRequest.

This is how looks my payload: enter image description here

and my method doPost:

    public void doPost(HttpServletRequest request,
        HttpServletResponse response)   throws ServletException, IOException {  
    response.setContentType("application/json");
    response.setCharacterEncoding("utf-8");
    PrintWriter out = response.getWriter();
        out.print("\"nie poprawne dane "+request.getReader()+"\"");     }

but it just show sth like this: nie poprawne dane org.apache.catalina.connector.CoyoteReader@1a10174e

This

out.print("\"nie poprawne dane "+request.getReader()+"\"");

will invoke request.getReader().toString(), which is not what you want. You should do this instead:

out.print("\\"nie poprawne dane "+request.getReader().readLine() +"\\"");

Still this solution is imcomplete, since it will only display one line if the payload has a newline character. You should probably do this:

try (final java.io.BufferedReader r = request.getReader()) {
    for (String l = r.readLine(); l != null; l = r.readLine()) {
       out.println(l);    
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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