通过 Apifox Echo 了解 Content-Length

970 阅读1分钟

Content-Length 用以指定 Body 的体积。响应头中的 Content-Length 指定 Response Body 的体积,请求头中的 Content-Length 指定 Request Body 的体积。

通过 Content-Length,HTTP 客户端/服务器端将会根据该头部计算出 Body 的大小。

请求头中的 Content-Length

fetch 等 HTTP 客户端中将会根据 Request Body 的体积自动计算出 Content-Length,所以,Content-Length 一般不需要手动指定。

但是,如果 Content-Length 指定体积过小,将无法传输完整的 Body。通过 Apifox Echo 示例如下。

# 指定 3,则只能接收到 a=3,body 将被截断
$ curl -X POST https://echo.apifox.com/post -d "a=3000" -H "content-length: 3"
{
  "args": {}, 
  "data": "", 
  "files": {}, 
  "form": {
    "a": "3"
  }, 
  "headers": {
    "Accept": "*/*", 
    "Content-Length": "3", 
    "Content-Type": "application/x-www-form-urlencoded", 
    "Host": "https://echo.apifox.com", 
    "User-Agent": "curl/7.79.1",
  }, 
  "json": null, 
  "url": "http://https://echo.apifox.com/post"
}

# 指定 4,则只能接收到 a=30,body 将被截断
$ curl -X POST https://echo.apifox.com/post -d "a=3000" -H "content-length: 3"
{
  "args": {}, 
  "data": "", 
  "files": {}, 
  "form": {
    "a": "30"
  }, 
  "headers": {
    "Accept": "*/*", 
    "Content-Length": "3", 
    "Content-Type": "application/x-www-form-urlencoded", 
    "Host": "https://echo.apifox.com", 
    "User-Agent": "curl/7.79.1",
  }, 
  "json": null, 
  "url": "http://https://echo.apifox.com/post"
}

# 指定 400,超过所要传递的 body 体积,则会卡住
$ curl -X POST https://echo.apifox.com/post -d "a=3000" -H "content-length: 400"

响应头中的 Content-Length

在 Apifox Echo 中,echo.apifox.com/response-headers 可指定服务器中的响应头,通过它可测试响应头的 Content-Length

$ curl https://echo.apifox.com/response-headers
{
  "Content-Length": "68", 
  "Content-Type": "application/json"
}

$ curl https://echo.apifox.com/response-headers?content-length=10
{
  "Conte

作业

  1. 如何得知请求报文/响应报文已接收完毕
  2. 使用 Apifox Echo 测试请求头和响应头中的 Content-Length