HttpServletRequest get JSON POST data

2022-08-31 07:11:31

我是 HTTP POST-ING 到 URL http://laptop:8080/apollo/services/rpc?cmd=execute

使用开机自检数据

{ "jsondata" : "data" }

Http 请求具有application/json; charset=UTF-8

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

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


答案 1

正常情况下,您可以在 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...
}

答案 2

您是否从不同的来源(因此不同的端口或主机名)发布?如果是这样,我刚刚回答的这个非常非常新的主题可能会有所帮助。

问题在于 XHR 跨域策略,以及有关如何使用称为 JSONP 的技术来绕过它的有用提示。最大的缺点是JSONP不支持POST请求。

我知道在原始帖子中没有提到JavaScript,但是JSON通常用于JavaScript,这就是为什么我跳到这个结论