我在 Spring 有这个 Controller
@RestController
public class GreetingController {
@RequestMapping(value = "/greeting", method = RequestMethod.POST)
public String greeting(@RequestParam("uouo") String uouo) {
return uouo;
}
}
当我测试它的时候
curl -k -i -X POST -H "Content-Type:application/json" -d uouo=test http://192.168.1.104:8080/api/greeting
测试结果
HTTP 状态 400 - 必需的字符串参数 'uouo' 不存在
我试过可能的事情,但我认为 @RequestParam
不能用于 POST,它总是使用 GET 在 URL 中传递参数,只有当我使用 @RequestBody
将对象 JSON 作为参数时,我才使用 post , 有什么方法可以使用 POST 发送字符串参数吗?
最佳答案
如果内容类型是 application/x-www-form-urlencoded
,Servlet 容器将只提供来自 POST 请求正文的参数。如果内容类型是其他类型,它将忽略正文。这在 Servlet Specification Chapter 3.1.1 When Parameters Are Available 中指定
The following are the conditions that must be met before post form data will be populated to the parameter set:
- The request is an HTTP or HTTPS request.
- The HTTP method is POST.
- The content type is
application/x-www-form-urlencoded
.- The servlet has made an initial call of any of the
getParameter
family of methods on the request object.If the conditions are not met and the post form data is not included in the parameter set, the post data must still be available to the servlet via the request object’s input stream. If the conditions are met, post form data will no longer be available for reading directly from the request object’s input stream.
由于您没有发送任何 JSON,只需设置适当的内容类型
curl -k -i -X POST -H "Content-Type:application/x-www-form-urlencoded" -d uouo=test http://192.168.1.104:8080/api/greeting
或者让 curl
推断它
curl -k -i -X POST -d uouo=test http://192.168.1.104:8080/api/greeting?uouo=test
请注意,您仍然可以在 URL 中传递查询参数
curl -k -i -X POST -H "Content-Type:application/json" http://192.168.1.104:8080/api/greeting?uouo=test
关于java - Spring REST Controller 发布请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29423320/