如何读取 Spring 引导控制器中的 post 数据?

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

我想从 Spring 引导控制器读取 POST 数据。

我已经尝试了这里给出的所有解决方案:,但我仍然无法读取 Spring 引导 servlet 中的 post 数据。

我的代码在这里:

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);
    }
}

我试过使用收集器作为替代方法,但也不起作用。我做错了什么?

首先,您需要将RequestMethod定义为POST。 其次,可以在String参数中定义一个@RequestBody注解

@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);
    }
}