Home >Java >javaTutorial >How to Access JSON POST Data in a Servlet Using HttpServletRequest?
Accessing JSON POST Data in HttpServletRequest
When making an HTTP POST request with JSON data in the body, retrieving the request data can be a challenge if the traditional getParameter method is used. This is because getParameter only works with key-value pairs encoded in "application/x-www-form-urlencoded" format.
However, for JSON data streams, a custom approach is necessary.
Custom Decoder for JSON Data
To access the JSON POST data, you need to utilize BufferedReader to process the raw data stream:
BufferedReader reader = request.getReader();
Example Using org.json Package
Below is an example that uses the popular org.json library to decode JSON POST data:
@Override public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { StringBuffer jb = new StringBuffer(); String line = null; try { while ((line = reader.readLine()) != null) jb.append(line); } catch (Exception e) { /*report an error*/ } try { JSONObject jsonObject = HTTP.toJSONObject(jb.toString()); } catch (JSONException e) { // crash and burn throw new IOException("Error parsing JSON request string"); } }
This code reads the JSON data and converts it into a JSONObject for further processing. You can then use methods like getInt, getString, and getJSONArray to extract the specific data you need.
The above is the detailed content of How to Access JSON POST Data in a Servlet Using HttpServletRequest?. For more information, please follow other related articles on the PHP Chinese website!