165

I am HTTP POST-ing to URL http://laptop:8080/apollo/services/rpc?cmd=execute

with POST data

{ "jsondata" : "data" }

Http request has Content-Type of application/json; charset=UTF-8

How do I get the POST data (jsondata) from HttpServletRequest?

If I enumerate the request params, I can only see one param, which is "cmd", not the POST data.

np_6
  • 514
  • 1
  • 6
  • 19
Lydon Ch
  • 8,637
  • 20
  • 79
  • 132
  • 7
    This is simple method to get request data `request.getReader().lines().collect(Collectors.joining())` – Dmitry Stolbov Feb 22 '17 at 06:17
  • 2
    the above mentioned throws stream already closed exception – Patrick Apr 03 '17 at 16:36
  • If you use the `getReader()` the stream will get closed, since originally it can only be read once. There are a number of alternatives on Wrapper implementations to allow multiple calls to `getReader()` – Felipe Leão Mar 05 '18 at 18:46
  • The easiest way you can solve this is using *Jackson*'s `ObjectMapper`. Its overloaded method `readValue` has a variation which accepts a `Reader` and a `Class`. What you end up with is: `new ObjectMapper().readValue(request.getReader(), YourBodyType.class)` - and there you have it. Short and slick. – Ionut Ciuta Sep 25 '18 at 20:44

2 Answers2

280

Normaly you can GET and POST parameters in a servlet the same way:

request.getParameter("cmd");

But only if the POST data is encoded as key-value pairs of content type: "application/x-www-form-urlencoded" like when you use a standard HTML form.

If you use a different encoding schema for your post data, as in your case when you post a json data stream, you need to use a custom decoder that can process the raw datastream from:

BufferedReader reader = request.getReader();

Json post processing example (uses 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...
}
Ganesh Krishnan
  • 7,155
  • 2
  • 44
  • 52
Kdeveloper
  • 13,679
  • 11
  • 41
  • 49
  • 3
    It seems like you can only get the post data from request.getReader *once*. Is this true? When I tried this myself, subsequent calls to get the post-data of the request fail. – B T Feb 16 '11 at 23:38
  • 11
    That's correct you can read the request body content only once. – Kdeveloper Feb 17 '11 at 11:56
  • this really saved my day...but what is getReader and how do the json data get populated there? is it specifically for JSON? or any other object ? any helpful links please. – rajesh_kw Mar 06 '14 at 10:03
  • Why not just to pass `getReader()` to json parser as here: http://stackoverflow.com/a/15109169/603516 ? This wouldn't require extra copy loop. – Vadzim Apr 28 '14 at 15:16
  • 5
    JSONObject jsonObject = HTTP.toJSONObject(jb.toString()); toJSONObject must have been moved to be a static method in the org.json.HTTP class – semisided1 Sep 26 '14 at 17:41
  • 1
    Why I cannot find the `fromObject(String string)` method inside the documentation? http://www.json.org/javadoc/org/json/JSONObject.html – XY L Feb 04 '15 at 08:42
  • 1
    @X.Li, see the comment directly above yours. – jds Feb 07 '15 at 22:15
  • You can use StringBuilder here, and you need close reader in finally block. Just in case :) – Mirimas Aug 27 '15 at 21:24
  • 1
    Should be: JSONObject jsonObject = new JSONObject(jb.toString()); – Newbie Jun 02 '17 at 03:49
  • get POST body `BufferedReader reader = request.getReader();` –  Jul 02 '18 at 03:29
-3

Are you posting from a different source (so different port, or hostname)? If so, this very very recent topic I just answered might be helpful.

The problem was the XHR Cross Domain Policy, and a useful tip on how to get around it by using a technique called JSONP. The big downside is that JSONP does not support POST requests.

I know in the original post there is no mention of JavaScript, however JSON is usually used for JavaScript so that's why I jumped to that conclusion

Community
  • 1
  • 1
CharlesLeaf
  • 3,201
  • 19
  • 16