问题

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

我是对URLhttp://laptop:8080/apollo/services/rpc?cmd=execute的HTTP POST

使用POST数据

{ "jsondata" : "data" }

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

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

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


#1 热门回答(245 赞)

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

request.getParameter("cmd");

但仅当POST数据是encoded的内容类型的键值对时:"application / x-www-form-urlencoded"就像使用标准HTML表单时一样。
如果对发布数据使用不同的编码模式,就像发布ajson数据流时的情况一样,则需要使用可以处理原始数据流的自定义解码器:

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 热门回答(0 赞)

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

  • 奇怪的jQuery问题 - 对C程序的Ajax请求不太正常

问题是XHR跨域策略,以及如何通过使用称为JSONP的技术解决它的有用提示。最大的缺点是JSONP不支持POST请求。
我知道在原帖中没有提到JavaScript,但是JSON通常用于JavaScript,这就是我跳到这个结论的原因


#3 热门回答(-11 赞)

发件人(php json编码):

{"natip":"127.0.0.1","natport":"4446"}

Receiver(java json decode):

/**
 * @comment:  I moved  all over and could not find a simple/simplicity java json
 *            finally got this one working with simple working model.
 * @download: http://json-simple.googlecode.com/files/json_simple-1.1.jar
 */

JSONObject obj = (JSONObject) JSONValue.parse(line); //line = {"natip":"127.0.0.1","natport":"4446"}
System.out.println( obj.get("natport") + " " + obj.get("natip") );     // show me the ip and port please

希望它对Web开发人员和简单的JSON搜索者有所帮助。


原文链接