Skip to content

HTTP Protocol: "Ngôn ngữ communication" FE-BE

Core

HTTP work thế nào? Như: 2 người đối thoại — cần ngôn ngữ, cú pháp, rule. HTTP là "protocol đối thoại" FE-BE.


0. Bản chất HTTP

HTTP (HyperText Transfer Protocol) = protocol nền cho FE-BE communication.

0.1 Ẩn dụ đối thoại

ElementHTTPNote
Ngôn ngữHTTP protocol2 bên đều hiểu
Cú phápRequest/response format"Nói" thế nào
FlowRequest-responseHỏi-đáp
Kết thúcTCP closeKết thúc

1. HTTP evolution

🌐HTTP 协议演示
📤HTTP 请求
GET/api/users/123HTTP/1.1
Host:api.example.com
User-Agent:Mozilla/5.0
Accept:application/json
Authorization:Bearer xxx
TCP 连接
📥HTTP 响应
HTTP/1.1200OK
Content-Type:application/json
Content-Length:156
Cache-Control:max-age=3600
{ "id": 123, "name": "张三", "email": "zhangsan@example.com" }
VersionYearCải tiếnĐặc trưng
HTTP/0.91991Chỉ GETText thuần, chỉ request, không header
HTTP/1.01996+ POST/HEADMỗi request 1 TCP connection
HTTP/1.11997Persistent connectionKeep-Alive, 1 connection nhiều request
HTTP/22015MultiplexingBinary frame, header compression
HTTP/32022Trên QUICUDP, giải head-of-line blocking

Sao cần HTTP/2?

HTTP/1.1 dù persistent, request phải serial (response trước → mới send request sau). HTTP/2 multiplexing giải — gửi song song nhiều request.


2. HTTP request structure

2.1 Request line

http
GET /api/users/123 HTTP/1.1

3 phần: method (GET, POST, PUT, DELETE), URL, version.

2.2 Request header

http
Host: api.example.com
User-Agent: Mozilla/5.0
Accept: application/json
Authorization: Bearer xxx
Content-Type: application/json
Content-Length: 45
HeaderNoteVd
HostServer domainapi.example.com
User-AgentClient infoMozilla/5.0
AcceptResponse type chấp nhậnapplication/json
AuthorizationAuth infoBearer token
Content-TypeRequest body typeapplication/json

2.3 Request body

json
{ "name": "Hoàng", "email": "h@example.com" }

Chỉ POST, PUT, PATCH có body.


3. HTTP response structure

3.1 Status line

http
HTTP/1.1 200 OK

3.2 Response header

http
Content-Type: application/json
Content-Length: 156
Cache-Control: max-age=3600
Set-Cookie: session=xxx; HttpOnly

3.3 Response body

json
{ "code": 0, "data": { "id": 123, "name": "Hoàng" } }

4. HTTP methods

MethodUseBodyIdempotentSafe
GETLấy resourceKhông
POSTTạo resourceKhôngKhông
PUTUpdate fullKhông
PATCHUpdate partialKhôngKhông
DELETEXoáKhôngKhông
HEADLấy headerKhông
OPTIONSQuery method hỗ trợKhông

4.1 GET vs POST

FeatureGETPOST
ParamURL queryBody
CacheCacheableDefault no
BookmarkBookmark đượcKhông
HistorySaveKhông save
LengthLimit (URL length)Không limit
SecurityParam visible URLParam trong body

5. Status codes

ClassNoteCodes
2xxSuccess200, 201, 204
3xxRedirect301, 302, 304
4xxClient error400, 401, 403, 404
5xxServer error500, 503
CodeNoteUse
200 OKSuccessGET, PUT success
201 CreatedCreatedPOST success
204 No ContentNo contentDELETE success
301 Moved PermanentlyPermanent redirectURL change permanent
302 FoundTemp redirectURL change temp
304 Not ModifiedNot modifiedCache valid
400 Bad RequestParam wrongFormat sai
401 UnauthorizedNo authCần login
403 ForbiddenNo permissionĐã login, không quyền
404 Not FoundNot existResource không tồn tại
429 Too Many RequestsRate limitedQuá rate limit
500 Internal Server ErrorServer crashApp exception
503 Service UnavailableUnavailableMaintenance / overload

6. HTTPS

6.1 HTTP vs HTTPS

FeatureHTTPHTTPS
ProtocolTCPTCP + SSL/TLS
Port80443
DataPlaintextEncrypted
CertKhông cầnSSL cert
PerfHơi nhanhHơi chậm (handshake overhead)
SEOKhông ảnh hưởngGoogle ưu tiên

6.2 HTTPS workflow

  1. Client Hello: client gửi cipher suite hỗ trợ
  2. Server Hello: server trả cert + cipher chọn
  3. Verify cert: client verify server cert
  4. Key exchange: asymmetric encryption đổi session key
  5. Encrypted comm: symmetric encryption với session key

HTTPS lợi

  • Anti-eavesdrop: data encrypt
  • Anti-tamper: data integrity check
  • Anti-impersonation: SSL cert verify server

7. HTTP cache

7.1 Cache headers

HeaderNoteVd
Cache-ControlCache strategymax-age=3600
ETagResource version"33a64df551425fcc"
Last-ModifiedLast modifiedWed, 21 Oct 2015 07:28:00 GMT

7.2 Cache strategies

Strong cache:

http
Cache-Control: max-age=3600

3600s, browser dùng cache trực tiếp, không gửi request.

Negotiation cache:

http
ETag: "33a64df551425fcc"

Browser gửi If-None-Match, server trả 304 (no modify) hoặc 200 (modified).


8. Common questions

8.1 GET vs POST bản chất

Misconception: chỉ khác param position.

Truth:

  • GET idempotent, multi request kết quả như nhau
  • POST không idempotent, multi request có thể tạo nhiều resource
  • GET cacheable, POST default không
  • GET bookmarkable, POST không

8.2 HTTP/1.1 head-of-line blocking

Problem: dù persistent, request phải serial. Response trước chậm → sau phải đợi.

Solutions:

  • HTTP/2 multiplexing
  • Domain sharding
  • Connection pool

8.3 HTTP/2 advantages

FeatureHTTP/1.1HTTP/2
FormatTextBinary frame
MultiplexingKhông
Header compressionKhôngHPACK
Server pushKhông

Glossary

TermFullNote
HTTPHyperText Transfer Protocol-
HTTPSHTTP SecureHTTP + SSL/TLS
TCPTransmission Control Protocol-
SSL/TLSSecure Sockets Layer-
Idempotent-Multi request kết quả giống nhau
Keep-Alive-1 TCP nhiều request
Multiplexing-Song song nhiều request
HoL BlockingHead-of-LineRequest trước block request sau

2026 cho VN dev

  • HTTP/3 + QUIC: mainstream, Cloudflare, Google, Facebook đều dùng
  • CDN VN: BunnyCDN, Cloudflare APAC support HTTP/3
  • API auth chuẩn: Bearer token (JWT), OAuth2 cho 3rd party
  • VN context: Banking API thường vẫn HTTP/1.1 legacy, e-commerce hiện đại = HTTP/2
  • Tool: HTTPie, Bruno, Insomnia (Postman alternatives)