🎯 核心区别
Content-Type:告诉服务器我发送的数据是什么格式Accept:告诉服务器我希望接收什么格式的响应数据
📋 详细说明
1. Content-Type (内容类型)
- 作用:描述请求体的格式
- 使用场景:当你的请求有请求体时(如POST、PUT请求)
- 示例:
Content-Type: application/json表示"我发送的是JSON格式的数据"
// 在MockMvc中设置Content-Type
mockMvc.perform(post("/api/users").contentType(MediaType.APPLICATION_JSON) // 告诉服务器请求体是JSON.content("{\"name\":\"John\", \"age\":30}"))
2. Accept (接受类型)
- 作用:描述客户端期望的响应格式
- 使用场景:任何请求(GET、POST、PUT、DELETE等)
- 示例:
Accept: application/json表示"我希望接收JSON格式的响应"
// 在MockMvc中设置Accept
mockMvc.perform(get("/api/users/1").accept(MediaType.APPLICATION_JSON)) // 期望服务器返回JSON
🔄 实际应用场景
场景1:POST请求发送JSON,期望返回JSON
// 这种情况需要同时设置Content-Type和Accept
mockMvc.perform(post("/api/users").contentType(MediaType.APPLICATION_JSON) // 我发送JSON.accept(MediaType.APPLICATION_JSON) // 我希望收到JSON.content("{\"name\":\"John\", \"age\":30}")).andExpect(status().isCreated());
场景2:GET请求,期望返回JSON
// 只有请求,没有请求体,所以只需要Accept
mockMvc.perform(get("/api/users").accept(MediaType.APPLICATION_JSON)) // 只设置Accept.andExpect(status().isOk());
场景3:POST请求发送JSON,不关心响应格式
// 只设置Content-Type,不设置Accept
mockMvc.perform(post("/api/users").contentType(MediaType.APPLICATION_JSON) // 只设置Content-Type.content("{\"name\":\"John\", \"age\":30}"));
📊 总结表格
| 参数 | 作用 | 使用场景 | 示例值 |
|---|---|---|---|
| Content-Type | 描述请求体格式 | POST、PUT等有请求体的操作 | application/json |
| Accept | 描述期望的响应格式 | 任何需要特定响应格式的操作 | application/json |
🛠️ 实际代码示例
完整的POST请求测试示例
@Test
public void testCreateUser() throws Exception {// 准备请求数据UserCreateRequest request = new UserCreateRequest("John", "john@example.com");String requestJson = new ObjectMapper().writeValueAsString(request);// 执行请求mockMvc.perform(post("/api/users").contentType(MediaType.APPLICATION_JSON) // 必须:请求体是JSON.accept(MediaType.APPLICATION_JSON) // 可选:期望JSON响应.content(requestJson)).andExpect(status().isCreated()).andExpect(jsonPath("$.id").exists()).andExpect(jsonPath("$.name").value("John"));
}
💡 记忆技巧
- Content-Type → 我发送什么 → 关注请求体
- Accept → 我接受什么 → 关注响应体
⚠️ 注意事项
- POST请求必须设置Content-Type,否则服务器不知道如何解析请求体
- Accept是可选的,如果不设置,服务器通常会返回默认格式
- 如果服务器不支持客户端请求的Accept格式,应该返回406状态码
所以,对于你的POST请求构建JSON的情况,必须设置Content-Type: application/json,而Accept根据你是否对响应格式有要求来决定是否设置。