首页 文章

HttpServletRequest获取JSON POST数据[重复]

提问于
浏览
147

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

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

使用POST数据

{ "jsondata" : "data" }

Http请求的内容类型为 application/json; charset=UTF-8

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

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

3 回答

  • -2

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

    request.getParameter("cmd");
    

    But only if the POST data is encoded as key-value pairs of content type: "application/x-www-form-urlencoded" like when you use a standard HTML form.

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

    BufferedReader reader = request.getReader();
    

    Json post processing example (uses org.json package )

    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...
    }
    
  • 251

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

    问题是XHR跨域策略,以及如何通过使用称为JSONP的技术解决它的有用提示 . 最大的缺点是JSONP不支持POST请求 .

    我知道在原帖中没有提到JavaScript,但是JSON通常用于JavaScript,这就是我跳到这个结论的原因

  • -10

    发件人(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搜索者有所帮助 .

相关问题