"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > Get JSON POST data method from HttpServletRequest

Get JSON POST data method from HttpServletRequest

Posted on 2025-04-15
Browse:171

How to Retrieve JSON POST Data from an HttpServletRequest?

Retrieving JSON POST Data from HttpServletRequest

When performing an HTTP POST request with JSON-encoded data, it's essential to understand the difference in data encoding compared to standard HTML form submissions. In this case, the POST data is not automatically accessible via the HttpServletRequest.getParameter() method.

To retrieve JSON POST data, you need to utilize a custom decoder that can process the raw data stream obtained from HttpServletRequest.getReader(). Here's an example using the org.json package:

public void doPost(HttpServletRequest request, HttpServletResponse response)
  throws ServletException, IOException {

  StringBuffer jb = new StringBuffer();
  String line = null;
  try {
    BufferedReader reader = request.getReader();
    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");
  }

  // Work with the data using methods like...
  // int someInt = jsonObject.getInt("intParamName");
  // String someString = jsonObject.getString("stringParamName");
  // JSONObject nestedObj = jsonObject.getJSONObject("nestedObjName");
  // JSONArray arr = jsonObject.getJSONArray("arrayParamName");
  // etc...
}

This code reads the raw JSON data from the request, parses it into a JSONObject, and provides access to the data within the object. You can then interact with the JSON data as needed, extracting the parameters and values you require.

Note that this approach is necessary when using JSON-encoded POST data instead of the traditional "application/x-www-form-urlencoded" encoding used in standard HTML forms. By utilizing a custom decoder, you can efficiently retrieve and process the JSON data in your Servlet application.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3