通过HttpServletRequest转换获得json对象

如何把前端传过来的Json对象解析出来?在java web应用中,我们如何获取post请求body中的内容?
通常利用request获取参数可以直接通过req.getParameter(name)的方式获取url上面或者ajax data提交上来的参数。但是body是没有名字的,无法通过参数名字这种方式获取。这时候需要用到io流的方式来获取body中的内容。

package com.example.controller;
 
import java.io.BufferedReader;
import java.io.InputStreamReader;
 
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
 
import com.alibaba.fastjson.JSONObject;
 
@RestController
@EnableAutoConfiguration
public class Example {
 
    @RequestMapping("/")
    String home() {
        return "Hello World!";
    }
    
    
    // 这里我没做异常处理
    @RequestMapping("/request")
    String request(HttpServletRequest request, HttpServletResponse response) {
        String param= null; 
        try {
            BufferedReader streamReader = new BufferedReader( new InputStreamReader(request.getInputStream(), "UTF-8"));
            StringBuilder responseStrBuilder = new StringBuilder();
            String inputStr;
            while ((inputStr = streamReader.readLine()) != null)
                responseStrBuilder.append(inputStr);
            
            JSONObject jsonObject = JSONObject.parseObject(responseStrBuilder.toString());
            param= jsonObject.toJSONString();
            System.out.println(param);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return param;
    }
    
    
    
    
 
    @RequestMapping("/hello/{myName}")
    String index(@PathVariable String myName) {
        return "Hello " + myName + "!!!";
    }
}

 

获取body参数,需要在request.getParameter()方法之前调用(如果有需要取QueryString参数的话),因为一旦调用了getParameter()方法之后,再通过IO流的方式获取body参数就失效了(亲测返回"")

 

参考:

1、http://blog.techbeta.me/2015/12/java-http-json/

2、https://blog.csdn.net/qq_27292113/article/details/76837603

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值