如何在 Spring 引导控制器中读取开机自检数据



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

我已经尝试了这里给出的所有解决方案:HttpServletRequest 获取 JSON POST 数据,但我仍然无法在 Spring Boot 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);
    }
}

最新更新