Java
HttpServletRequest
POST request
Servlet
Web Development

Get the POST request body from HttpServletRequest in Java

Codemia Knowledge Hub ·

Read the body through request.getReader() (for text) or request.getInputStream() (for raw bytes) inside doPost. For text, a common pattern is to loop over the BufferedReader line by line and collect the result in a StringBuilder.

Reading the POST body with getReader()

java
1import java.io.BufferedReader;
2import java.io.IOException;
3import javax.servlet.ServletException;
4import javax.servlet.annotation.WebServlet;
5import javax.servlet.http.HttpServlet;
6import javax.servlet.http.HttpServletRequest;
7import javax.servlet.http.HttpServletResponse;
8
9@WebServlet("/postHandler")
10public class PostHandlerServlet extends HttpServlet {
11    protected void doPost(HttpServletRequest request, HttpServletResponse response)
12            throws ServletException, IOException {
13        StringBuilder builder = new StringBuilder();
14        try (BufferedReader reader = request.getReader()) {
15            String line;
16            while ((line = reader.readLine()) != null) {
17                builder.append(line).append('\n');
18            }
19        }
20        String requestBody = builder.toString();
21        
22        // Process your request body
23        System.out.println("Received POST body: " + requestBody);
24    }
25}

Things to get right:

  • Character encoding: call request.setCharacterEncoding("UTF-8") before reading, or special characters can be decoded incorrectly.
  • Content type: the client should send a matching type, such as application/json for JSON or application/x-www-form-urlencoded for form data.
  • Idempotency: unlike GET, POST is not idempotent, so repeating a request can produce a different result.

Parsing a JSON body with Gson or Jackson

Once you have the body as a string, hand it to a JSON library such as Gson or Jackson:

java
1import com.google.gson.Gson;
2//...
3
4String jsonString = builder.toString();
5MyObject obj = new Gson().fromJson(jsonString, MyObject.class);

Large bodies, concurrency and errors

  • Data size: reading a large body into one string can strain memory. Process the stream in chunks instead.
  • Concurrency: with many clients sending large data, manage shared resources carefully.
  • Error handling: check for read failures and malformed data and respond accordingly.
ComponentDescription
MethoddoPost()
Reading InputBufferedReader reader = request.getReader();
Character Encodingrequest.setCharacterEncoding("UTF-8");
Data Typesapplication/json, application/x-www-form-urlencoded
JSON Parsing LibrariesGson and Jackson
Handling Large DataStream processing for memory efficiency
Error HandlingChecks and responses for malformed data or I/O exceptions

Testing and securing POST handling

Test against different character encodings and formats, using tools like Postman or JUnit tests. Always validate and sanitize input to protect against injection attacks, and enforce HTTPS for transmission.


Course
Intermediate
27 lessons
14 hours
OOD Fundamentals

Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.

View the course
Data Structures & Algorithms practice on Codemia

Step through 300+ coding interview problems with animated visualisers that show the data structure changing as the code runs. The Blind 75 are free.

Practice algorithms