格式:type/subtype(;parameter)?
text、application、image)html、json、png)charset=utf-8)| 類別 | Content-Type | 用途 |
|---|---|---|
| text | text/html | HTML 頁面 |
| text/plain | 純文字 | |
| text/xml | XML 資料 | |
| image | image/gif/jpeg/png | 圖片格式 |
| application | application/json | JSON 資料(最常用) |
| application/xml | XML 資料 | |
| application/pdf | PDF 文件 | |
| application/msword | Word 文件 | |
| application/octet-stream | 二進制流(檔案下載) | |
| application/x-www-form-urlencoded | 表單預設編碼 | |
| application/xhtml+xml | XHTML | |
| multipart/form-data | 檔案上傳(必須) |
@RequestMapping(
value = "/path",
method = RequestMethod.POST,
consumes = "application/json", // 限制請求 Content-Type
produces = "application/json" // 限制回應 Content-Type,且需匹配 Accept 頭
)
| 屬性 | 作用 | 對應 HTTP 頭 |
|---|---|---|
| consumes | 過濾請求內容類型 | Content-Type |
| produces | 指定回應類型,匹配 Accept | Accept |
| headers | 任意請求頭過濾 | 任意 Header |
| params | 請求參數過濾 | Query/String 參數 |
@RequestMapping(value = "/test", method = RequestMethod.GET,
headers = "Referer=https://www.ifeng.com/")
public void testHeaders() { ... }
@RequestMapping(value = "/response/ContentType",
headers = "Accept=application/json")
public void response2(HttpServletResponse response) throws IOException {
response.setContentType("application/json;charset=utf-8");
response.getWriter().write("{\"username\":\"zhang\", \"password\":\"123\"}");
}
Accept 匹配規則:明確度優先 > 品質因子 q 值大優先。
例:Accept: application/xml;q=0.5, application/json;q=0.9, text/html → 匹配順序:text/html > application/json > application/xml
@RequestMapping(value = "/test/{userId}", method = RequestMethod.GET,
params = "myParam=myValue")
public void findUser(@PathVariable String userId) { ... }
@Controller
@RequestMapping(value = "/users", method = RequestMethod.POST,
consumes = "application/json", produces = "application/json")
@ResponseBody
public List<User> addUser(@RequestBody User user) {
// 處理邏輯
return users;
}
僅處理 Content-Type: application/json 的請求,且要求 Accept 包含 application/json,回應亦為 JSON。
文中包含完整的 Request Headers(Accept、Authorization、Cookie、Content-Type 等 30+ 項)與 Response Headers(Cache-Control、Content-Encoding、ETag、Location、Set-Cookie 等 20+ 項)對照表,開發除錯時可直接查閱。