HttpServletRequest获取JSON POST数据 [英] HttpServletRequest get JSON POST data
问题描述
我是HTTP发布到URL http:// laptop:8080 / apollo / services / rpc?cmd =执行
I am HTTP POST-ing to URL http://laptop:8080/apollo/services/rpc?cmd=execute
使用
POST数据
with POST data
{ "jsondata" : "data" }
Http请求的Content-Type为应用/ JSON; charset = 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.
推荐答案
Normaly你可以用同样的方式在servlet中获取和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 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屋!