HTTP Note #1: HTTP Basics

为什么必须了解 HTTP ?

Zhihu 上有个问答:前端工程师应该对 HTTP 了解到什么程度?从哪些途径去熟悉更好? 原来一个好的 web dev 不是只需懂得 HTML、CSS、JavaScript 即可,想要深入下去,熟悉 HTTP 协议必不可少,所以决定直接读 RFC 2616,至少重点要细读。


背景(参考 Wikipedia

Hypertext Transfer Protocol (HTTP) 是应用层的传输协议,www 文件都要遵守这个标准,第一版协议为 HTTP/0.9 ,现在已过时。接下来的版本是 RFC 1945 定义的 HTTP/1.0 ,然而,现在被广泛使用的版本是 HTTP/1.1(由 RFC 2616 定义)。

HTTP 1.0 与 HTTP 1.1 的区别

  • 缓存处理
  • 带宽优化及网络连接的使用
  • 错误通知的管理
  • 消息在网络中的发送
  • 互联网地址的维护
  • 安全性及完整性

HTTP message

HTTP Request message format

Request message,从客户端发往服务端,结构分成三部分:request line, header line & entity body

  • request line: 所有元素用 SP 字符分开,举一个经过解析的直观栗子:

    GET http://www.w3.org/pub/WWW/TheProject.html HTTP/1.1
    
  • header line (or request-header fields): 非必需,允许从客户端传送关于 Request 的附加信息。可从 general-header | request-header | entity-header 这三类 header 中选取,未能被识别的 header field 会被当做 entity-header field。

  • entity body 是 entity 的一部分。entity 作为 request / response 的负载信息,包括 entity-header 与 entity-body。

HTTP Response message format

Response message 是服务器在接受并解释了 request 后发送的响应信息,和 Request message 相比,除了第一部分 request line 被替换为 status line 之外,在结构上是一样的。

!注意: 除了作为结尾的 CRLF 外(entity body 并不需要),不允许出现单独的 CR 或 LF 字符。


拓展

以上大部分 token 通过字面意思可以理解其用处,但是自己无法直接理解 SP,CR,LF,其中:

  • SP ( Space ) 空格
  • CR ( Carriage Return ) 回车
  • LF ( Line Feed ) 换行

CR & LF 都是源自传统打字机时代的术语:

It (Carriage Return) was used after typing a line of text and caused the assembly holding the paper (the carriage) to return to the right so that the machine was ready to type again on the left-hand side of the paper (assuming a left-to-right language)

– from wikipedia Carriage return

The concepts of line feed (LF) and carriage return (CR) are closely associated and can be either considered separately or lumped together. In the physical media of typewriters and printers, two axes of motion, “down” and “across”, are needed to create another line (a new line) on the page.

(突然觉得回车键( ↵ (U+21B5))相当之形象~)

Although the design of a machine (typewriter or printer) must consider them separately, the abstract logic of software can lump them together as one event. This is why a newline in character encoding can be defined as LF and CR combined into one (LF+CR, LFCR, CR+LF, CRLF).

– from wikipedia Newline

终于明白为什么回车键是 return,为什么协议中非要将 CR LF 连在一块儿使用。


感想

  • 在学习 HTTP 协议的过程中,时不时有一种正在自学计网课的穿越感,深切感到基础课还是灰常重要滴,如果没有计网打底,自己死磕 HTTP 协议想必会非常辛苦。

  • HTTP协议详解很清楚就能够了解个大概。但是《HTTP权威指南》和直接读 RFC 2616,不知道如何比较难易。RFC 2616 定于1999年6月,十五年过去了,尽管 HTTP 协议还有许多不完美的地方,比如不够安全等等,但是毕竟已经被广泛使用了这么多年。现在自己决定直接读 RFC 2616,也许会更枯燥些,不过毕竟是标准,总是不会有大错的。

问题

  • entity body 以何结尾?

    The end-of-line marker within an entity-body is defined by its associated media type.

    – from RFC 2616

    从这句话中猜测可能与 MIME 类型有关,现在对 MIME 不熟悉,以后补上。

  • 不知道哪一些知识点是重中之重,写着写着就开始钻到细节里,抓不住重点。现在只能一视同仁,每一点都先学起来。

计划

  • 接下来会详细看 Request message 中每一个 token。