首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

HTTP Content-Type 詳解與 Spring MVC 中的消費/產出媒體型別映射實戰

     編輯:Java 相關知識

Content-Type 基礎

格式:type/subtype(;parameter)?

  • type:主類型(如 text、application、image)
  • subtype:子類型(如 html、json、png)
  • parameter:可選參數(如 charset=utf-8)

常見媒體類型速查

類別Content-Type用途
texttext/htmlHTML 頁面
text/plain純文字
text/xmlXML 資料
imageimage/gif/jpeg/png圖片格式
applicationapplication/jsonJSON 資料(最常用)
application/xmlXML 資料
application/pdfPDF 文件
application/mswordWord 文件
application/octet-stream二進制流(檔案下載)
application/x-www-form-urlencoded表單預設編碼
application/xhtml+xmlXHTML
multipart/form-data檔案上傳(必須)

Spring MVC @RequestMapping 媒體類型屬性

@RequestMapping(
    value = "/path",
    method = RequestMethod.POST,
    consumes = "application/json",  // 限制請求 Content-Type
    produces = "application/json"   // 限制回應 Content-Type,且需匹配 Accept 頭
)

屬性對照表

屬性作用對應 HTTP 頭
consumes過濾請求內容類型Content-Type
produces指定回應類型,匹配 AcceptAccept
headers任意請求頭過濾任意 Header
params請求參數過濾Query/String 參數

實戰範例

1. headers 精確匹配

@RequestMapping(value = "/test", method = RequestMethod.GET,
    headers = "Referer=https://www.ifeng.com/")
public void testHeaders() { ... }

2. produces 搭配 Accept 品質因子

@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

3. params 參數過濾

@RequestMapping(value = "/test/{userId}", method = RequestMethod.GET,
    params = "myParam=myValue")
public void findUser(@PathVariable String userId) { ... }

4. consumes/produces 完整應用

@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。

常見請求/回應 Headers 速查

文中包含完整的 Request Headers(Accept、Authorization、Cookie、Content-Type 等 30+ 項)與 Response Headers(Cache-Control、Content-Encoding、ETag、Location、Set-Cookie 等 20+ 項)對照表,開發除錯時可直接查閱。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved