HttpServletRequest獲取body && 使用 @RequestBody 獲取body

直接從HttpServletRequest的Reader流中獲取請求body參數

	@RequestMapping(value = "/nty=", method = RequestMethod.POST)
    public JSONObject ForwardNtyMsg(HttpServletRequest request) throws IOException {
        // 直接從HttpServletRequest的Reader流中獲取RequestBody
        BufferedReader reader = request.getReader();
        StringBuilder builder = new StringBuilder();
        String line = reader.readLine();
        while(line != null){
            builder.append(line);
            line = reader.readLine();
        }
        reader.close();

        String reqBody = builder.toString();
        System.out.println("recv json data:" + reqBody);

        // string 2 jsonobject
        JSONObject json = JSONObject.parseObject(reqBody);
        
        System.out.println("recv ntydel from:" + request.getRequestURI());
        
		// todo..

        // return
        JSONObject retjson = new JSONObject();
        retjson.put("recv", "success");
        return retjson;
    }

使用 @RequestBody 獲取body

	@RequestMapping(value = "/nty", method = RequestMethod.POST)
    public JSONObject ForwardNtyMsg(@RequestBody JSONObject jsonString, HttpServletRequest httpServletRequest) {
        System.out.println("recv nty json data:" + jsonString.toJSONString());

        System.out.println("recv nty from:" + httpServletRequest.getRequestURI());
        
		// todo..
		
        // return
        JSONObject json = new JSONObject();
        json.put("recv", "success");
        return json;
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章