跳轉到

What You Should Know About HTTP

img

HTTP/1.1

1. Cache Control

2. Persistent Connection

img

3. Request Pipelining

img

HTTP/2

1. Multiplexing

Multiplexing will allow multiple requests and response messages to retrieve resources in a single TCP connection simultaneously. img

2. Header Compression

Each request via HTTP contains header information. With HTTP/1.1, many headers are repeated in one session and duplicate the same info.

This overhead is considerable, HTTP/2 removes the excess header while pressing the remaining headers and forcing all HTTP headers to be sent in a compressed format.

3. Server Push

With HTTP/1.1 it must wait for the client to send the connection.

Server Push allows the server to avoid delays in sending data by “pushing” responses that it claims the client needs to cache it and automatically this will speed up page load time by reducing the number of requests. img

4. Binary Format

HTTP/1.1 sends data in the textual format, while HTTP/2 sends data in binary format. Binary protocols are more efficient to parse and reduce the number of errors, compared to previous versions of textual protocols. img

常見 HTTP 狀態碼

2xx

  • 200 (OK) 請求成功了,並且把結果傳回
  • 204 (No Content) 跟 200 相似,不過沒有結果需要返回,DELETE 和 PUT 會常用
  • 202 (Accepted) 伺服器收到請求,並且確定請求是沒問題的 這單純代表收到了工作,不代表工作做完了 一般來說,工作完成後伺服器會主動推送結果給客戶端

3xx

  • 304 (Not Modified) 如果客戶端已經有了某一物件的副本,但是不知道這 物件是否最新版本,客戶端會發出 Conditional-GET,在 HTTP header 中加入 If-Modified-Since: <某時間> 如果客戶端版本是最新的,便回答 304 。否則便是 200

4xx

  • 400 (Bad Request) 請求的內容有誤,伺服器拒絕執行,例子:Age 這個資料應該是 Integer 的,客戶端卻傳來 ABC123
  • 401 (Unauthorized) 請先登入系統 請檢查 HTTP HEADER 的 Authorization
  • 403 (Forbidden) 跟 400 不同,伺服器明白請求的內容 不過,其請求內容與商業邏輯矛盾,伺服器拒絕執行 例子:建立一個貓的物件,其{心愛食物=洋蔥}
  • 404 (Not Found) 請求的資源不存在,例子:www.abc.com/v1/users/89073 ,而系統並沒有 89073 這用戶 如果是 GET collection 而沒搜尋到滿足條件的物件,是應該返回 200 ,而不是 404,例子:www.abc.com/v1/users?AgeMin=30&AgeMax=20
  • 409 (Conflict) 通常跟 optimistic lock 有關 這是指用戶正在改動的物件,已經被別人先改動過了。
  • 410 (Gone) 一個資源曾經存在,但現在不再存在 大部份懶人會用 404 電商東西賣光了是回傳 403,而不是 410

5xx

5XX 系列的錯誤,全都是用戶/客戶端無法自行解決的

  • 500 (Internal Server Error) 伺服器程式有 bug ,或是某部份(例如資料庫)當掉了
  • 502 (Bad Gateway) 伺服器端的分流器層(load balancing tier)出現問題
  • 503 (Service Unavailable) 伺服器沒當掉,只是目前太多人使用而繁忙中,所以先直接拒絕這個請求