如何获取HttpServletRequest中邮递员发送的myObject的正文

时间:2019-06-14 10:12:02

标签: controller

我在spring boot应用程序中有一个控制器,我想获取要在邮递员,json对象中发送的信息的主体...

关于从httpServletRequest读取正文,我已经尝试了关于stackoverflow的所有解决方案,但这些都不起作用

这只是应该返回正文的代码示例之一,但并非如此

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

-有很多示例,但是从stackoverflow上介绍的示例来看,它们都无法工作 -当我使用getReader()时,出现此异常“此请求已调用getInputStream()-IllegalStateException” -当我使用getInputStream()而不是getReader()时,我得到的是空字符串体...

我要从中获取httpServletRequest正文的控制器

@PreAuthorizeMethod(value = CREATE_OBJECT)
    @ApiOperation(value = "Create an objectCreateDTO",
            response = ResponseMessage.class)
    @RequestMapping(value = {"/be/license-template", "/api/license-template"},
            method = RequestMethod.POST,
            consumes = MediaType.APPLICATION_JSON_VALUE,
            produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseMessage createObject(@RequestBody @Valid MyObject myObjectCreateDTO, BindingResult bindingResult, HttpServletResponse httpServletResponse, HttpServletRequest servletRequest) {

        ObjectMapper mapper = new ObjectMapper();
        ServletInputStream inputStream;
        try {
            inputStream = servletRequest.getInputStream();
            Book book = mapper.readValue(inputStream, Book.class);
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (bindingResult.hasErrors()) {
            ResponseMessage responseMessage = new ResponseMessage(null, VALIDATE_MESSAGE_FAILURE);
            logger.debug("License template failed to be created!");
            return controllerUtil.populateResponseMessageWithErrors(responseMessage, bindingResult, httpServletResponse);
        }
        //some service code written here
        return new ResponseMessage(myObjectCreateDTO, OBJECT_CREATED_WITH_SUCCESS);
    }

我只想获取请求的正文,仅此而已。 控制器中使用的ObjectMapper代码取自stackoverflow,它不起作用,出现错误“流关闭” 请告诉我我在做什么错?

0 个答案:

没有答案