How do I read the post data in a Spring Boot Controller?

99封情书 提交于 2021-01-28 01:41:51

问题


I would like to read POST data from a Spring Boot controller.

I have tried all the solutions given here: HttpServletRequest get JSON POST data, but I still am unable to read post data in a Spring Boot servlet.

My code is here:

package com.testmockmvc.testrequest.controller;

import org.apache.commons.io.IOUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

@Controller
public class TestRequestController {

    @RequestMapping(path = "/testrequest")
    @ResponseBody
    public String testGetRequest(HttpServletRequest request) throws IOException {
        final byte[] requestContent;
        requestContent = IOUtils.toByteArray(request.getReader());
        return new String(requestContent, StandardCharsets.UTF_8);
    }
}

I have tried using the Collectors as an alternative, and that does not work either. What am I doing wrong?


回答1:


First, you need to define the RequestMethod as POST. Second, you can define a @RequestBody annotation in the String parameter

@Controller
public class TestRequestController {

    @RequestMapping(path = "/testrequest", method = RequestMethod.POST)
    public String testGetRequest(@RequestBody String request) throws IOException {
        final byte[] requestContent;
        requestContent = IOUtils.toByteArray(request.getReader());
        return new String(requestContent, StandardCharsets.UTF_8);
    }
}


来源:https://stackoverflow.com/questions/48348158/how-do-i-read-the-post-data-in-a-spring-boot-controller

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!