一、HTTP请求方法体系(含15种标准方法)
核心方法矩阵
方法 | 安全性 | 幂等性 | 典型场景 | 请求体 | 响应体 |
---|---|---|---|---|---|
GET | ✔️ | ✔️ | 查询资源列表/详情 | ❌ | ✔️ |
POST | ❌ | ❌ | 创建新资源/表单提交 | ✔️ | ✔️ |
PUT | ❌ | ✔️ | 全量更新资源 | ✔️ | ✔️ |
DELETE | ❌ | ✔️ | 删除指定资源 | ❌ | ✔️ |
扩展方法详解
方法 | 应用场景 | 特殊说明 |
---|---|---|
HEAD | 检查资源元数据 | 仅返回响应头 |
OPTIONS | 跨域预检/CORS机制 | 返回Allow头声明支持方法 |
PATCH | 局部更新资源 | 需指定Content-Type头 |
TRACE | 诊断请求回显 | 存在XST攻击风险,生产环境禁用 |
CONNECT | 建立隧道连接(HTTPS代理) | 仅限代理服务器使用 |
WebDAV扩展方法
方法 | 功能描述 | 典型应用 |
---|---|---|
MOVE | 资源移动操作 | 文件系统类API |
COPY | 资源复制操作 | 云存储服务API |
LINK | 建立资源关联 | 社交网络关系链构建 |
UNLINK | 移除资源关联 | 反向关联解除 |
二、Spring Boot全场景实现示例
1. 核心方法实现
GET请求:带分页查询
@GetMapping("/users")
public Page<User> getUsers(
@RequestParam(defaultValue = "0") int page,
@RequestParam(defaultValue = "10") int size) {
// 分页查询逻辑
Page<User> users = userRepository.findAll(PageRequest.of(page, size));
return users;
}
特性验证:多次请求URL参数不变时返回相同结果
POST请求:文件上传
@PostMapping("/upload")
public ResponseEntity<String> uploadFile(
@RequestPart("file") MultipartFile file,
@RequestParam String description) {
// 文件存储逻辑
return ResponseEntity.ok("File uploaded successfully");
}
安全注意:需配置MultipartResolver处理大文件上传
2. 数据操作方法
PUT请求:版本控制更新
@PutMapping("/products/{id}")
public ResponseEntity<Product> updateProduct(
@PathVariable Long id,
@RequestBody ProductUpdateDTO updateDTO) {
// 实现乐观锁控制
Product product = productService.updateWithVersion(id, updateDTO);
return ResponseEntity.ok(product);
}
幂等验证:重复提交相同数据不会产生副作用
PATCH请求:JSON Merge Patch
@PatchMapping(value = "/users/{id}",
consumes = MediaType.APPLICATION_MERGE_PATCH_JSON_VALUE)
public ResponseEntity<User> partialUpdate(
@PathVariable Long id,
@RequestBody UserPatchDTO patch) {
// 实现局部更新
User updated = userService.partialUpdate(id, patch);
return ResponseEntity.ok(updated);
}
格式要求:必须使用application/merge-patch+json
3. 特殊方法实现
OPTIONS预检请求
@OptionsMapping("/api/orders")
public ResponseEntity<CorsConfiguration> corsOptions() {
CorsConfiguration config = new CorsConfiguration();
config.addAllowedMethod(HttpMethod.POST);
config.addAllowedHeader("Authorization");
return ResponseEntity.ok(config);
}
CORS机制:自动处理浏览器跨域预检请求
TRACE请求(禁用示例)
@TraceMapping
public ResponseEntity<String> traceEndpoint() {
// 生产环境应返回405 Method Not Allowed
return ResponseEntity.status(405).build();
}
安全配置:需在Spring Security中显式禁用
三、RESTful API设计规范
方法选择决策树
graph TD
A[需要操作资源?] -->|读取数据| B[GET]
A -->|创建资源| C[POST]
A -->|更新资源| D{是否全量更新?}
D -->|是| E[PUT]
D -->|否| F[PATCH]
A -->|删除资源| G[DELETE]
最佳实践清单
- 幂等性保障:PUT/PATCH需设计幂等逻辑,可通过唯一请求ID实现
- 参数校验:使用
@Valid
注解配合Hibernate Validator@PostMapping public void create(@Valid @RequestBody OrderRequest request) { // 自动触发参数校验 }
- 错误处理:统一异常响应格式
@ExceptionHandler(MethodNotAllowedException.class) public ErrorResponse handleMethodNotAllowed() { return new ErrorResponse("METHOD_NOT_ALLOWED", "不支持的请求方法"); }
四、进阶调试技巧
1. 使用cURL测试
# 带认证的PATCH请求
curl -X PATCH \
-H "Content-Type: application/merge-patch+json" \
-H "Authorization: Bearer xxx" \
-d '{"status":"ACTIVE"}' \
https://api.example.com/users/123
2. Postman配置
- 方法选择:直接选择目标HTTP方法
- Headers设置:添加
Content-Type
等必要头信息 - 测试断言:使用Test脚本验证响应状态码