Skip to content

HTTP Protocol: The "Communication Language" Between Frontend and Backend

Core Question

How does HTTP work? It's like asking: how do two people hold a conversation? They need to agree on a language, grammar, and conversation rules. HTTP is the "conversation protocol" between frontend and backend.


0. The Essence of HTTP

HTTP (HyperText Transfer Protocol) is the foundational protocol for frontend-backend communication.

0.1 Conversation Analogy

Conversation ElementHTTP EquivalentDescription
LanguageHTTP protocolA language both sides can understand
GrammarRequest/response formatHow to "speak"
FlowRequest-response patternOne question, one answer
EndingHang upTCP connection closes

1. HTTP's Evolution

HTTP has undergone several major upgrades since its creation in 1991.

🌐HTTP Protocol Demo
📤HTTP request
GET/api/users/123HTTP/1.1
Host:api.example.com
User-Agent:Mozilla/5.0
Accept:application/json
Authorization:Bearer xxx
TCP connection
📥HTTP response
HTTP/1.1200OK
Content-Type:application/json
Content-Length:156
Cache-Control:max-age=3600
{ "id": 123, "name": "Alice", "email": "alice@example.com" }

1.1 Version Comparison

VersionYearCore ImprovementKey Feature
HTTP/0.91991Only supported GETPlain text only, no response headers
HTTP/1.01996Added POST/HEADOne TCP connection per request
HTTP/1.11997Persistent connectionsKeep-Alive, multiple requests per connection
HTTP/22015MultiplexingBinary frames, header compression
HTTP/32022Based on QUICUDP transport, solves head-of-line blocking

Why HTTP/2?

Although HTTP/1.1 supports persistent connections, requests must be sent sequentially (the next request can only be sent after the previous response returns). HTTP/2 solves this problem through multiplexing, allowing multiple requests to be sent simultaneously.


2. Structure of an HTTP Request

2.1 Request Line

http
GET /api/users/123 HTTP/1.1

Contains three parts:

  • Method: GET, POST, PUT, DELETE, etc.
  • URL: The resource path being requested
  • Version: HTTP/1.1 or HTTP/2

2.2 Request Headers

http
Host: api.example.com
User-Agent: Mozilla/5.0
Accept: application/json
Authorization: Bearer xxx
Content-Type: application/json
Content-Length: 45

Common request headers:

HeaderDescriptionExample
HostServer domainapi.example.com
User-AgentClient informationMozilla/5.0
AcceptAccepted response typesapplication/json
AuthorizationAuthentication informationBearer token
Content-TypeRequest body typeapplication/json

2.3 Request Body

json
{
  "name": "Zhang San",
  "email": "zhangsan@example.com"
}

Only POST, PUT, PATCH, and similar methods have a request body.


3. Structure of an HTTP Response

3.1 Status Line

http
HTTP/1.1 200 OK

Contains three parts:

  • Version: HTTP/1.1
  • Status code: 200, 404, 500, etc.
  • Status text: OK, Not Found, etc.

3.2 Response Headers

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

Common response headers:

HeaderDescriptionExample
Content-TypeResponse body typeapplication/json
Content-LengthResponse body size156
Cache-ControlCache policymax-age=3600
Set-CookieSet Cookiesession=xxx

3.3 Response Body

json
{
  "code": 0,
  "data": {
    "id": 123,
    "name": "Zhang San"
  }
}

4. HTTP Methods in Detail

MethodPurposeRequest BodyIdempotentSafe
GETRetrieve resourceNoneYesYes
POSTCreate resourceYesNoNo
PUTFull updateYesYesNo
PATCHPartial updateYesNoNo
DELETEDelete resourceNoneYesNo
HEADGet headers onlyNoneYesYes
OPTIONSQuery supported methodsNoneYesYes

4.1 GET vs POST

FeatureGETPOST
Parameter locationURL query parametersRequest body
CachingCacheableNot cached by default
BookmarksCan be bookmarkedCannot
Browser historySaved in historyNot saved
Data lengthLimited (URL length)Unlimited
SecurityParameters visible in URLParameters in request body

When to Use GET/POST?

  • GET: Query, retrieve data
  • POST: Create, submit data
  • PUT: Full update (replace the entire resource)
  • PATCH: Partial update (only modify specified fields)
  • DELETE: Delete a resource

5. HTTP Status Codes

5.1 Status Code Categories

CategoryDescriptionTypical Status Codes
2xxSuccess200 OK, 201 Created, 204 No Content
3xxRedirection301 Permanent, 302 Temporary, 304 Not Modified
4xxClient error400 Bad Request, 401 Unauthorized, 404 Not Found
5xxServer error500 Internal Server Error, 503 Service Unavailable

5.2 Common Status Codes

Status CodeDescriptionUse Case
200 OKRequest succeededSuccessful GET, PUT request
201 CreatedResource createdSuccessful POST creating a resource
204 No ContentNo contentSuccessful DELETE
301 Moved PermanentlyPermanent redirectURL permanently changed
302 FoundTemporary redirectURL temporarily changed
304 Not ModifiedNot modifiedCache still valid
400 Bad RequestBad requestMalformed request parameters
401 UnauthorizedUnauthorizedLogin required
403 ForbiddenForbiddenLogged in but insufficient permissions
404 Not FoundNot foundResource doesn't exist
500 Internal Server ErrorInternal errorServer exception
503 Service UnavailableUnavailableServer maintenance or overload

6. HTTPS: Secure HTTP

6.1 HTTP vs HTTPS

FeatureHTTPHTTPS
ProtocolTCPTCP + SSL/TLS
Port80443
DataPlaintextEncrypted
CertificateNot requiredSSL certificate required
PerformanceSlightly fasterSlightly slower (handshake overhead)
SEONo effectSearch engines prioritize HTTPS

6.2 How HTTPS Works

  1. Client Hello: Client sends supported cipher suites
  2. Server Hello: Server returns certificate and selected cipher suite
  3. Certificate verification: Client verifies the server certificate's validity
  4. Key exchange: Use asymmetric encryption to exchange a session key
  5. Encrypted communication: Use the session key for symmetric encryption

HTTPS Advantages

  • Anti-eavesdropping: Data is encrypted; third parties cannot read it
  • Anti-tampering: Data integrity verification
  • Anti-impersonation: SSL certificates verify server identity

7. HTTP Caching Mechanism

7.1 Cache Headers

HeaderDescriptionExample
Cache-ControlCache policymax-age=3600
ETagResource version identifier"33a64df551425fcc"
Last-ModifiedLast modified timeWed, 21 Oct 2015 07:28:00 GMT

7.2 Caching Strategies

Strong caching:

http
Cache-Control: max-age=3600

Within 3600 seconds, the browser uses the cache directly without sending a request.

Negotiated caching:

http
ETag: "33a64df551425fcc"

The browser sends If-None-Match; the server returns 304 (not modified) or 200 (modified).


8. Common Questions

8.1 The Real Difference Between GET and POST

Misconception: The only difference between GET and POST is where parameters are placed.

The truth:

  • GET is idempotent; multiple requests produce the same result
  • POST is non-idempotent; multiple requests may create multiple resources
  • GET can be cached; POST is not cached by default
  • GET can be bookmarked; POST cannot

8.2 HTTP/1.1 Head-of-Line Blocking

The problem: Although HTTP/1.1 supports persistent connections, requests must be sent sequentially. If a previous request's response is slow, all subsequent requests must wait.

Solutions:

  • HTTP/2 multiplexing
  • Domain sharding (multiple domains for multiple connections)
  • Connection pooling (limiting concurrency)

8.3 HTTP/2 Advantages

FeatureHTTP/1.1HTTP/2
Transmission formatTextBinary frames
MultiplexingNot supportedSupported
Header compressionNoneHPACK algorithm
Server pushNot supportedSupported

Glossary

TermFull NameDescription
HTTPHyperText Transfer ProtocolThe foundational web communication protocol
HTTPSHTTP SecureHTTP + SSL/TLS
TCPTransmission Control ProtocolReliable transport protocol
SSL/TLSSecure Sockets LayerSecurity protocol layer
Idempotent-Multiple requests produce the same result
Keep-Alive-Sending multiple requests over one TCP connection
Multiplexing-Sending multiple requests simultaneously
Head-of-Line Blocking-Earlier requests blocking later ones