马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。
您需要 登录 才可以下载或查看,没有账号?立即注册
×
🎯 核心区别
- 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/jsonAccept形貌渴望的相应格式任何须要特定相应格式的使用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根据你是否对相应格式有要求来决定是否设置。
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。 |