问题
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