java - HttpServletRequest 获取 JSON POST 数据

我正在 HTTP POST 到 URL http://laptop:8080/apollo/services/rpc?cmd=execute

与 发布数据

{ "jsondata" : "data" }

Http请求的Content-Type为application/json; charset=UTF-8

如何从 HttpServletRequest 获取 POST 数据(jsondata)?

如果我枚举请求参数,我只能看到一个参数, 这是“cmd”,而不是 POST 数据。

最佳答案

通常您可以在 servlet 中以相同的方式获取和发布参数:

request.getParameter("cmd");

但前提是 POST 数据为 encoded作为内容类型的键值对:“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...
}

https://stackoverflow.com/questions/3831680/

相关文章:

python - 如何将网页中的 JSON 转换为 Python 脚本

jquery - TypeError : $. ajax(...) 不是函数?

javascript - 在 JavaScript 中将 JSON 字符串解析为特定的对象原型(pr

ios - 如何使用 NSJSONSerialization

ios - 如何将 JSON 字符串反序列化为 NSDictionary? (适用于 iOS 5+)

python - 存储 Python 字典

javascript - JSON 省略了 Infinity 和 NaN; ECMAScript 中

php - json_encode() 转义正斜杠

python - 如何在 Python 中检查字符串是否是有效的 JSON?

python - 将类实例序列化为 JSON