HttpServletRequest 获取 JSON POST 数据 [英] HttpServletRequest get JSON POST data
问题描述
我正在 HTTP POST 到 URL http://laptop:8080/apollo/services/rpc?cmd=execute
I am HTTP POST-ing to URL http://laptop:8080/apollo/services/rpc?cmd=execute
与POST数据
{ "jsondata" : "data" }
Http 请求的 Content-Type 为 application/json;字符集=UTF-8
Http request has Content-Type of application/json; charset=UTF-8
如何从 HttpServletRequest 获取 POST 数据(jsondata)?
How do I get the POST data (jsondata) from HttpServletRequest?
如果我枚举请求参数,我只能看到一个参数,这是cmd",而不是 POST 数据.
If I enumerate the request params, I can only see one param, which is "cmd", not the POST data.
推荐答案
通常你可以用同样的方式在 servlet 中 GET 和 POST 参数:
Normaly you can GET and POST parameters in a servlet the same way:
request.getParameter("cmd");
但仅当 POST 数据被编码为内容类型的键值对时:application/x-www-form-urlencoded"就像您使用标准 HTML 表单一样.
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.
如果您对发布数据使用不同的编码模式,例如发布 json 数据流,您需要使用自定义解码器来处理来自以下位置的原始数据流:
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 后处理示例(使用 org.json 包)
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...
}
这篇关于HttpServletRequest 获取 JSON POST 数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!