无法使用@RequestBody?那就使用HttpServletRequest吧

背景

最近在对接第三方开放平台,需要按照标准提供一个事件推送接口,接口实现demo声明如下:

public Map<String, String> callBack(
@RequestParam(value = "msg_signature", required = false) String msg_signature,
@RequestParam(value = "timestamp", required = false) String timeStamp,
@RequestParam(value = "nonce", required = false) String nonce,
@RequestBody(required = false) JSONObject json) {
}

从代码上看,如果项目是基于SpringBoot的,那么可以完全没有问题。但是本次对接的项目历史悠久,还没切换到SpringBoot框架,所以只能寻求解决方案。

解决

对于注解@RequestBody实际解析的也是Http post请求中body的内容,那我们是否可以转而通过解析http body获取到请求内容呢? 答案是肯定的,方案奉上,来自万能的stackoverflowhttps://stackoverflow.com/questions/8100634/get-the-post-request-body-from-httpservletrequest,这里的核心就是HttpServletRequest,链接里面有几种解决方案可选择。

高赞回答1:

该方案基于原始java代码解析。

if ("POST".equalsIgnoreCase(request.getMethod())) 
{
   test = request.getReader().lines().collect(Collectors.joining(System.lineSeparator()));
}

高赞回答2:

基于commons-io包直接实现。

IOUtils.toString(request.getReader());

对于我遇到的场景,最终需要将其解析为JSONObject,所以直接使用了方案2.
代码如下:

private JSONObject getHttpBody(HttpServletRequest request) throws IOException {
    String httpContent = IOUtils.toString(request.getReader());
    log.info("getHttpBody, body:{}", httpContent);
    return JSON.parseObject(httpContent);
}

验证

测试代码

@PostMapping("/httpServlet")
public String httpServlet(HttpServletRequest servletRequest) {
    try {
        JSONObject data = getHttpBody(servletRequest);
        return JSON.toJSONString(data);
    } catch (Exception e) {
        return e.getMessage();
    }
}

@PostMapping("/requestBody")
public String requestBody(@RequestBody JSONObject data) {
    try {
        return JSON.toJSONString(data);
    } catch (Exception e) {
        return e.getMessage();
    }
}

private JSONObject getHttpBody(HttpServletRequest request) throws IOException {
    String httpContent = IOUtils.toString(request.getReader());
    log.info("getHttpBody, body:{}", httpContent);
    return JSON.parseObject(httpContent);
}

验证通过
在这里插入图片描述
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

51iwowo

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值