通过 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/