正常情况下,您可以在 servlet 中以相同的方式获取和 POST 参数:
request.getParameter("cmd");
但前提是将 POST 数据编码为内容类型的键值对:“application/x-www-form-urlencoded”,就像使用标准 HTML 表单一样。
如果对帖子数据使用不同的编码架构(例如发布 json 数据流时的情况),则需要使用自定义解码器来处理来自以下位置的原始数据流:
BufferedReader reader = request.getReader();
Json 后处理示例(使用 org.json 包)
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...
}