java - 记录不带正文但包含路径和查询参数的 PUT REST 调用

标签 java spring-restdocs

通过 HTTP PUT 设计的 REST API 调用只有路径和查询参数,不需要正文:

PUT /posts/{id}/read?currentUser={loginId} 

尝试使用 Spring REST Docs 2.0.0.RELEASE 记录它,我注意到 http-request.adoc 如下:

[source,http,options="nowrap"]
----
PUT /posts/42?currentUser=johndoe HTTP/1.1
Host: localhost:8080
Content-Type: application/x-www-form-urlencoded

currentUser=johndoe
----

我很困惑,为什么 currentUser=johndoe 在正文中呈现(如表单参数)?这是一个错误吗?完整的应用示例如下:

@RestController
@RequestMapping("/posts")
@SpringBootApplication
public class DemoApplication {

    @PutMapping("{id}/read")
    public void markPostRead(@PathVariable("id") String id, @RequestParam("currentUser") String login) {
        System.out.println("User " + login + " has read post " + id);
    }

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
}
@RunWith(SpringRunner.class)
@WebMvcTest
public class DemoApplicationTests {

    @Rule
    public JUnitRestDocumentation restDocumentation = new JUnitRestDocumentation();
    private MockMvc mockMvc;

    @Autowired
    private WebApplicationContext context;

    @Before
    public void setUp() {
        this.mockMvc = MockMvcBuilders.webAppContextSetup(this.context)
                .apply(documentationConfiguration(this.restDocumentation))
                .build();
    }
    @Test
    public void contextLoads() throws Exception {
        mockMvc.perform(
                RestDocumentationRequestBuilders.put("/posts/{id}/read?currentUser=johndoe", 42))
                .andDo(document("mark-as-read", pathParameters(
                        parameterWithName("id").description("ID of the Post")
                )))
                .andDo(document("mark-as-read", requestParameters(
                        parameterWithName("currentUser").description("Login ID of user")
                )));
    }

}

最佳答案

如果你学习RFC 2616 with special attention on the PUT section你会读到……

The PUT method requests that the enclosed entity be stored under the supplied Request-URI.

所以问题是,尽管规范在这部分并不是 100% 明确:是否允许发送完全没有请求正文的 PUT 请求?

如果你询问 10 个开发人员,这是你会得到 11 个答案的问题之一,但为了解决所有不可估量的问题,Spring REST 文档将你的查询参数放在请求正文中,只是为了为所有那些更严格的问题做好准备那里有网络服务器。 ;-)

关于java - 记录不带正文但包含路径和查询参数的 PUT REST 调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49561390/

相关文章:

java - 如何在没有浏览器的情况下在客户端进行打印?

java - 解决 ConcurrentModificationException

java - 调用传递请求和响应的方法将文件存储到 MYSQL 数据库时出错

java - 如何以一种好的方式在 Java 中的同一个列表中查找对象对

spring-mvc - Spring Rest Docs 如何在我的代码片段或 .adoc 文件中包含应用程序名称

grails - 是否可以直接在 grails 中使用 Spring MVC Test,如何使用?

java - 模数问题

java - 如何使用 Spring REST Docs 将顶级数组记录为响应负载

java - 是否可以将 Spring Restdocs 与 Jersey 应用程序一起使用

spring-restdocs - spring-rest-docs 应用程序在运行或集成测试时不会生成片段