如何在Spring Boot Controller中读取帖子数据?

atu*_*tul 2 spring spring-boot spring-restcontroller

我想从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);
    }
}
Run Code Online (Sandbox Code Playgroud)

我曾尝试使用收集器作为替代方案,但这也不起作用.我究竟做错了什么?

fmo*_*dos 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);
    }
}
Run Code Online (Sandbox Code Playgroud)