无法使用@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);
}

验证通过
无法使用@RequestBody?那就使用HttpServletRequest吧_第1张图片
无法使用@RequestBody?那就使用HttpServletRequest吧_第2张图片

你可能感兴趣的:(java,spring,boot,servlet)