HttpServletRequest获取JSON POST数据

Don*_* Ch 156 java post json servlets

可能重复:
从HttpServletRequest检索JSON对象文字

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

使用POST数据

{ "jsondata" : "data" }
Run Code Online (Sandbox Code Playgroud)

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

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

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

Kde*_*per 263

Normaly你可以用同样的方式在servlet中获取和POST参数:

request.getParameter("cmd");
Run Code Online (Sandbox Code Playgroud)

但是,只有将POST数据编码为内容类型的键值对:"application/x-www-form-urlencoded",就像使用标准HTML表单一样.

如果对发布数据使用不同的编码模式,就像发布json数据流时的情况一样,则需要使用可以处理原始数据流的自定义解码器:

BufferedReader reader = request.getReader();
Run Code Online (Sandbox Code Playgroud)

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...
}
Run Code Online (Sandbox Code Playgroud)

  • 这是正确的,你只能阅读一次请求正文内容. (10认同)
  • JSONObject jsonObject = HTTP.toJSONObject(jb.toString()); 必须将toJSONObject移动为org.json.HTTP类中的静态方法 (5认同)
  • 看起来你只能从request.getReader*获取post数据*.这是真的?当我自己尝试这个时,后续调用获取请求的后期数据失败. (3认同)

Cha*_*eaf -3

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

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

我知道在原来的帖子中没有提到 JavaScript,但是 JSON 通常用于 JavaScript,所以这就是我得出这个结论的原因