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()
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/jsonfor JSON orapplication/x-www-form-urlencodedfor 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:
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.
| Component | Description |
| Method | doPost() |
| Reading Input | BufferedReader reader = request.getReader(); |
| Character Encoding | request.setCharacterEncoding("UTF-8"); |
| Data Types | application/json, application/x-www-form-urlencoded |
| JSON Parsing Libraries | Gson and Jackson |
| Handling Large Data | Stream processing for memory efficiency |
| Error Handling | Checks 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.
Related reading
- Get type of a generic parameter in Java with reflection
- Get Value of a Edit Text field
- Get value of a public static field via reflection
- getResourceAsStream returns null
- getResourceAsStream vs FileInputStream
- getString Outside of a Context or Activity
- Getting Ambiguous ExceptionHandler method mapped for MethodArgumentNotValidException while startup of spring boot application
- Getting an element from a Set
System design interview problems on this topic
- Design an API Rate Limiter: solution and walkthrough
- Design a Distributed Messaging System: solution and walkthrough
- Design an Online Payment Service: solution and walkthrough
- Design a Key Value Store: solution and walkthrough

OOD Fundamentals
Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.
View the courseData 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.