HTTP Content-Type深入實(shí)踐

引子

HTTP是一種網(wǎng)絡(luò)應(yīng)用層傳輸協(xié)議,協(xié)議就是約定。HTTP頭部字段Content-Type約定請(qǐng)求和響應(yīng)的HTTP body內(nèi)容編碼類(lèi)型,客戶(hù)端和服務(wù)端根據(jù)HTTP頭部字段Content-Type正確解碼HTTP body內(nèi)容。
常見(jiàn)的HTTP頭部Content-Type:

  • application/x-www-form-urlencoded
  • multipart/form-data
  • application/json
  • application/xml

當(dāng)然還有更多的類(lèi)型,比如請(qǐng)求html時(shí)是text/html,請(qǐng)求css時(shí)是text/css,請(qǐng)求js時(shí)是text/javascript...
本文將深入實(shí)踐Content-Type對(duì)HTTP body內(nèi)容的解碼重要性,模擬發(fā)送HTTP頭部Content-Type:application/json,后端使用Spring boot+Java,前端使用html+javascript+css+jquery。
Content-Type和Content-Length焦不離孟,關(guān)于Content-Length可以參考拙作HTTP Content-Length深入實(shí)踐

HTTP Request Content-Type

前端使用Content-Type:"application/json"編碼HTTP請(qǐng)求內(nèi)容并提交給服務(wù)端,服務(wù)端使用Content-Type:"application/json"解碼HTTP請(qǐng)求內(nèi)容。下面實(shí)踐HTTP Request頭部Content-Type的作用。
后端Spring boot+Java代碼如下,Product類(lèi)包含三個(gè)字段:id,name,price,請(qǐng)自建并引入。

package com.demo.web.http;

import com.demo.domain.http.Product;
import com.google.common.collect.Maps;
import com.google.gson.Gson;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("http")
public class ContentTypeController {
    @RequestMapping("/content-type-request")
    public String contentType4Request() {
        return "http/content-type-request";
    }

    @RequestMapping("content-type-request.json")
    @ResponseBody
    public void json4Request(@RequestBody List<Product> products, HttpServletResponse response) throws IOException {
        System.out.println(Arrays.deepToString(products.toArray()));
        response.getWriter().write("Add products success.");
    }
}

前端html+javascript+css+jquery代碼如下:

<!DOCTYPE HTML>
<html>
<head>
    <title>HTTP request Content-Type Demo</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <script src="http://code.jquery.com/jquery-1.11.3.min.js" type="text/javascript"></script>
</head>
<body>
<button type="button" onclick="addProducts();">向服務(wù)器發(fā)送json</button>
<p id="msg"></p>
<script>
    var products = new Array();
    products.push({
        id : 1,
        name : "iPhone 6 Plus",
        price : 4987.5
    });
    products.push({
        id : 2,
        name : "iPhone 7 Plus",
        price : 5987.5
    });
    function addProducts() {
        $.ajax({
            type: "POST",
            url: "content-type-request.json",
            data: JSON.stringify(products),
            contentType: "application/json",
            dataType: "text",
            success: function (result) {
                console.log(result);
                $("#msg").html(result);
            },
            error: function () {
                alert("error.");
            }
        });
    }
</script>
</body>
</html>

如圖1,點(diǎn)擊“向服務(wù)器發(fā)送json”按鈕,ajax請(qǐng)求頭部Content-Type:application/json,ajax請(qǐng)求后端方法com.demo.web.http.ContentTypeController#json4Request,后端方法解碼HTTP請(qǐng)求內(nèi)容的products json字段,并打印出來(lái)。

圖1 HTTP request Content-Type:application/json

當(dāng)把前端代碼的contentType: "application/json",注釋?zhuān)岸隧?yè)面報(bào)如下錯(cuò)誤:

圖2 HTTP Request頭部Content-Type使用默認(rèn)值

圖3 HTTP Request頭部Content-Type使用默認(rèn)值

從圖2、圖3看,如果不明確指定HTTP Request頭部Content-Type,將使用application/x-www-form-urlencoded; charset=UTF-8作為默認(rèn)值,后端方法com.demo.web.http.ContentTypeController#json4Request不能解碼Content-Type:application/x-www-form-urlencoded的HTTP Request body內(nèi)容,返回HTTP 415錯(cuò)誤:不支持的媒體類(lèi)型(Unsupported media type)。如下后端報(bào)錯(cuò)信息也印證這點(diǎn),說(shuō)明后端方法com.demo.web.http.ContentTypeController#json4Request只能解碼請(qǐng)求頭部Content-Type為application/json的HTTP Request body內(nèi)容。
2017-07-23 17:03:56.917 WARN 24723 --- [nio-8080-exec-2] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved exception caused by Handler execution: org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'application/x-www-form-urlencoded;charset=UTF-8' not supported

HTTP Response Content-Type

服務(wù)端使用Content-Type:"application/json"編碼HTTP響應(yīng)body內(nèi)容返回給前端,前端使用Content-Type:"application/json"解碼HTTP響應(yīng)body內(nèi)容。下面實(shí)踐HTTP Response頭部Content-Type的作用。

情況1:服務(wù)端返回Response Content-Type:application/json,前端dataType不指定值

后端Spring boot+Java代碼如下:

package com.demo.web.http;

import com.google.common.collect.Maps;
import com.google.gson.Gson;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

@Controller
@RequestMapping("http")
public class ContentTypeController {
    private final static Gson GSON = new Gson();
    @RequestMapping("/content-type-response")
    public String contentType4Response() {
        return "http/content-type-response";
    }

    @RequestMapping("content-type-response.json")
    @ResponseBody
    public void json4Response(HttpServletResponse response) throws IOException {
        Map<String, Object> map = Maps.newHashMap();
        map.put("name", "datou");
        response.setContentType("application/json;charset=utf-8");
        response.getWriter().write(GSON.toJson(map));
    }
}

前端html+javascript+css+jquery代碼如下:

<!DOCTYPE HTML>
<html>
<head>
    <title>HTTP response Content-Type Demo</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <script src="http://code.jquery.com/jquery-1.4.2.min.js" type="text/javascript"></script>
</head>
<body>
<p>Name: <span id="name"></span></p>
<button onclick="show()">show name</button>
<script>
    function show() {
        $.get("content-type-response.json", function (data) {
            console.log(data);
            $("#name").text(data.name);
        });
    }
</script>
</body>
</html>

如圖4,點(diǎn)擊“show name”按鈕,ajax請(qǐng)求后端方法com.demo.web.http.ContentTypeController#json4Response,后端方法返回HTTP響應(yīng)頭部Content-Type:application/json,前端$.get()方法在不指定dataType具體值的情況下解碼HTTP響應(yīng)body內(nèi)容,data類(lèi)型是Object,js獲取并展示data.name的內(nèi)容。

圖4 服務(wù)端返回Response Content-Type:application/json,前端$.get() dataType不指定值

情況2:服務(wù)端不返回Response Content-Type:application/json,前端dataType指定值json

后端Spring boot+Java代碼注釋response.setContentType("application/json;charset=utf-8");
前端html+javascript+css+jquery代碼如下,前端dataType指定值"json":

<!DOCTYPE HTML>
<html>
<head>
    <title>HTTP response Content-Type Demo</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <script src="http://code.jquery.com/jquery-1.4.2.min.js" type="text/javascript"></script>
</head>
<body>
<p>Name: <span id="name"></span></p>
<button onclick="show()">show name</button>
<script>
    function show() {
        $.get("content-type-response.json", function (data) {
            console.log(data);
            $("#name").text(data.name);
        }, "json");
    }
</script>
</body>
</html>

如圖5,點(diǎn)擊“show name”按鈕,ajax請(qǐng)求后端方法com.demo.web.http.ContentTypeController#json4Response,后端方法返回HTTP響應(yīng)沒(méi)有頭部字段Content-Type,前端$.get()指定dataType="json"解碼HTTP響應(yīng)body內(nèi)容,data類(lèi)型是Object,js獲取并展示data.name的內(nèi)容。

圖5 服務(wù)端不返回Response Content-Type:application/json,前端dataType指定值"json"

情況3:服務(wù)端不返回Response Content-Type:application/json,前端dataType不指定值"json"

后端Spring boot+Java代碼注釋response.setContentType("application/json;charset=utf-8");
前端html+javascript+css+jquery代碼如下,前端$.get()dataType不指定值"json"

<!DOCTYPE HTML>
<html>
<head>
    <title>HTTP response Content-Type Demo</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <script src="http://code.jquery.com/jquery-1.4.2.min.js" type="text/javascript"></script>
</head>
<body>
<p>Name: <span id="name"></span></p>
<button onclick="show()">show name</button>
<script>
    function show() {
        $.get("content-type-response.json", function (data) {
            console.log(data);
            $("#name").text(data.name);
        });
    }
</script>
</body>
</html>

如圖6,點(diǎn)擊“show name”按鈕,ajax請(qǐng)求后端方法com.demo.web.http.ContentTypeController#json4Response,后端方法返回HTTP響應(yīng)不返回頭部字段Content-Type,前端$.get()在不指定dataType具體值為"json"的情況下不能解碼HTTP響應(yīng)body的json字符串,data類(lèi)型是String,js不能獲取data.name值,所以展示的Name:為空。

圖6 服務(wù)端不返回Response Content-Type:application/json,前端dataType不指定值"json"

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀(guān)點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容

  • Spring Cloud為開(kāi)發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見(jiàn)模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 134,993評(píng)論 19 139
  • http頭部字段Content-Type約定請(qǐng)求和響應(yīng)的HTTP body內(nèi)容編碼類(lèi)型,客戶(hù)端和服務(wù)端根據(jù)http...
    番薯大佬閱讀 2,328評(píng)論 1 1
  • 引子 HTTP頭部Content-Length用于描述HTTP消息實(shí)體的傳輸長(zhǎng)度,瀏覽器對(duì)比Content-Len...
    大頭8086閱讀 26,387評(píng)論 1 6
  • Android 自定義View的各種姿勢(shì)1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 173,559評(píng)論 25 708
  • 巖腳侗寨是其實(shí)是在一月份(二十六)去的 因著剛換了工作 一直沒(méi)時(shí)間更 今天閑下來(lái)了 想著該動(dòng)動(dòng)手了...
    公子段_閱讀 783評(píng)論 0 0