Home > Java > javaTutorial > How to Retrieve JSON POST Data Using HttpServletRequest?

How to Retrieve JSON POST Data Using HttpServletRequest?

Susan Sarandon
Release: 2024-12-19 21:19:15
Original
848 people have browsed it

How to Retrieve JSON POST Data Using HttpServletRequest?

HttpServletRequest: Retrieving JSON POST Data

In your web application, you're sending a POST request to a specific URL with JSON data, and you're using HttpServletRequest to access the POST data. However, when you enumerate the request parameters, you can only find the "cmd" parameter but not the JSON data.

Typically, you can obtain GET and POST parameters in a servlet using the request.getParameter("paramName") method. This works well when the POST data is encoded as key-value pairs with a content type of "application/x-www-form-urlencoded," as seen in standard HTML forms.

In your case, since you're sending a JSON data stream, you need to employ a custom decoder to process the raw data stream accessible from request.getReader(). Here's an example of how you can handle JSON POST processing:

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...
}
Copy after login

In summary, if you're dealing with JSON POST data, you need to use a custom decoder to process it directly from the request body, rather than relying on the built-in parameter enumeration mechanism.

The above is the detailed content of How to Retrieve JSON POST Data Using HttpServletRequest?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template