2010-09-30 46 views
141

可能重复:
Retrieving JSON Object Literal from HttpServletRequestHttpServletRequest的GET JSON POST数据

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

与 POST数据

{ "jsondata" : "data" } 

Http request has Content-Type application/json; charset=UTF-8

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

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

+2

这是获取请求数据'request.getReader()。lines()的简单方法。collect(Collectors.joining())' – 2017-02-22 06:17:35

+0

上面提到的throws stream已经关闭异常 – Pat 2017-04-03 16:36:21

+0

如果使用'getReader()'这个流将被关闭,因为它最初只能被读取一次。在包装器实现方面有很多方法可以允许多次调用getReader()' – 2018-03-05 18:46:16

回答

0

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

问题是XHR跨域策略,以及如何通过使用一种叫做JSONP技术来绕过它一个有用的技巧。最大的缺点是JSONP不支持POST请求。

我知道在原岗位没有JavaScript的提及,但是JSON通常用于JavaScript的所以这就是为什么我跳这个结论

233

Normaly你可以在同一个servlet GET和POST参数方法:

request.getParameter("cmd"); 

但是,只有当POST数据是encoded内容类型的键值对:“应用程序/ x-WWW的形式,进行了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... 
} 
+3

看起来好像你只能从request.getReader *中获得一次*后的数据。这是真的?当我自己尝试此操作时,后续调用以获取请求的后数据失败。 – 2011-02-16 23:38:45

+10

这是正确的,你只能读取请求主体内容一次。 – Kdeveloper 2011-02-17 11:56:04

+0

这确实节省了我的一天......但getReader是什么,以及json数据如何在那里填充?这是专门针对JSON吗?或任何其他物体?任何有用的链接,请。 – 2014-03-06 10:03:38

-11

发件人(PHP JSON编码):

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

接收器(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搜索。

+0

我需要这段代码的副本用于我的研究。确保社区表决其删除,但我必须为我的个人研究为私有。 – YumYumYum 2017-10-10 06:13:10