• 务器我希望接收什么格式的响应数据

📋 详细说明

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"));

更多推荐