HttpServletRequest获取JSON POST数据(HttpServletRequest get JSON POST data)
Possible Duplicate:
Retrieving JSON Object Literal from HttpServletRequest
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.
盾畳圭宛
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) { }
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…
}
还没有评论,来说两句吧...