🎯 核心區別

  • 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 → 我接受什麼 → 關注響應體

⚠️ 注意事項

  1. POST請求必須設置Content-Type,否則服務器不知道如何解析請求體
  2. Accept是可選的,如果不設置,服務器通常會返回默認格式
  3. 如果服務器不支持客户端請求的Accept格式,應該返回406狀態碼

所以,對於你的POST請求構建JSON的情況,必須設置Content-Type: application/json,而Accept根據你是否對響應格式有要求來決定是否設置。

作者:倉儲大叔,張佔嶺,