java - Spring REST Controller 发布请求

标签 java spring-mvc servlets

我在 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:

  1. The request is an HTTP or HTTPS request.
  2. The HTTP method is POST.
  3. The content type is application/x-www-form-urlencoded.
  4. 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/

相关文章:

java - 在 ServletOutputStream 中写入字节时管道损坏

java - 如果 session 因其他原因重置,如何将请求参数设置为在 session 中可用

java - LinearLayout 不显示项目

java - 我是否为每个实例变量编写了 javadoc 注释?

java - 无法使用 php exec 执行 jar 文件,尽管它可以在终端中运行

java - 比较不同格式的两个日期

java - spring data jpa repo,为什么需要接口(interface)服务和服务实现

使用 Spring 和 Hibernate 的 java.lang.NoSuchMethodError : antlr. collections.AST.getLine()

java - 内存监控包含 RabbitMQ 监听器的应用程序的 Java 堆大小使用情况

java - Openshift - 找不到适用于 jdbc 的驱动程序 :mysql