HTTP
特性:
- 无状态。无需建立持久连接,客户端发送一个请求,服务端返回响应,连接就被关闭了。
传输流程:
1. 地址解析
- url:http://mysite.com:8080/index.htm
- 协议名:http
- 主机名:mysite.com
- 端口:8080
- 路径:/index.htm
这一步中,需要 DNS 解析域名 mysite.com,得到主机的 IP
2. 封装 HTTP 请求数据包
3. 封装成 TCP 包并建立连接
再将 HTTP 数据包封装成 TCP 报文,建立 TCP 连接
4. 客户机发送请求命令
建立连接后,客户端发送一个请求给服务端,请求方式的格式为:URL、协议版本号,接着是 MIME 信息(包括请求修饰符、客户端信息和可能的内容)
5. 服务器响应
服务器接到请求后,给予相应的响应信息,其格式为一个状态行,包括信息的协议版本号、一个成功或
错误的代码,接着是 MIME 信息(包括服务器信息、实体信息和可能的内容)。
6. 服务器关闭 TCP 连接
一般情况下,一个 HTTP 请求和响应完成后,就会关闭 TCP 连接。但是如果请求的时候 HTTP 头带有 Connection:keep-alive,表示使用长连接,则 TCP 连接在完成第一次 HTTP 请求后仍然保持打开状态。长连接节省了 TCP 连接建立的时间,还节省了网络带宽。
HTTP状态码
wiki:https://zh.wikipedia.org/wiki/HTTP%E7%8A%B6%E6%80%81%E7%A0%81
1xx
- 100:Continue
- 101:Switching Protocol
-
2xx
200:OK
- 201:Created
- 202:Accepted
- 203:Non-Authoritative Information
- 204:No Content
- 205:Reset Content
-
3xx
300:Multiple Choices
- 301:Moved Permanently
- 302:Found
- 303:See Other
- 304:Not Modified
- 305:Use Proxy
- 306:Switch Proxy
- 307:Temporary Redirect
-
4xx
400:Bad Request
- 401:Unauthorized
- 402:Payment Required
- 403:Forbidden
- 404:Not Found
- 405:Method Not Allowed
- 406:Not Acceptable
- 407:Proxy Authentication Required
- 408:Request Timeout
- 409:Conflict
- 410:Gone
- 411:Length Required
- 412:Precondition Failed
- 413:Request Entity Too Large
- 414:Request-URI Too Long
- 415:Unsupported Media Type
- 416:Requested Range Not Satisfiable
-
5xx
500:Internal Server Error
- 501:Not Implemented
- 502:Bad Gateway
- 503:Service Unavailable
- 504:Gateway Timeout
- 505:HTTP Version Not Supported
请求过程:
浏览器发起一个 HTTP 请求的整个过程:
HTTP -> TCP -> IP -> MAC
DNS
先判断目标地址是否在本网络,不是的话发给默认网关,使用 ARP 协议将目标 IP 转换成 MAC。
路由器/猫使用 NAT,进行地址转换,然后发给公网。
公网各种路由协议,到达目标服务器
目标服务器将 IP 数据包向上层交付,到 HTTP 浏览器。
Java 的 Socket 是支持使用域名的。