HttpServletRequest获取JSON POST数据

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

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

与POST数据

{ "jsondata" : "data" } 

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

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

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

通常你可以用同样的方法在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... } 

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

  • 奇怪的jQuery问题 – Ajax请求到一个C程序不太工作

问题在于XHR跨域策略,以及如何通过使用名为JSONP的技术来解决这个问题。 最大的缺点是JSONP不支持POST请求。

我知道在原来的文章中没有提到JavaScript,但是JSON通常用于JavaScript,所以我就跳到了这个结论

发件人(php json编码):

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

Receiver(java json解码):

 /** * @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搜索器。