HTTP class


HTTP class

HTTP related knowledge

Features of HTTP protocol

No connection, no state, simple, fast and flexible

HTTP connection mode

Non persistent connection

Each request / reply client and server create a new connection and disconnect immediately after completion

HTTP class

Keep alive

Persistent connection makes the connection between client and server persistent and avoid re establishing connection when subsequent request to server appears.

HTTP class
Non pipeline

One request one response

Assembly line (pipeline)

Send multiple HTTP requests in batches, and do not need to wait for the response of the other party during the sending process. Pipelining does not affect the order in which responses arrive, only supported by HTTP / 1.1

HTTP message

HTTP class
Request message: request line, header line (request header), empty line, request body.
response message: status line, header line (response header), blank line, response body.

HTTP method

  • GET: get resources
  • POST: transfer resources
  • PUT: update resources
  • DELETE: delete resource
  • HEAD: get message header

Get and post requests

HTTPTwo methods of sending requests in the protocol. In essenceTCPConnection, no difference. But becauseHTTPBecause of the limitation of browser / server, they are different in the application process.

  1. getIt is generally used for query operations,postIt is generally used for commit operations.
  2. getParameters are passed through the URL,postPut it in request body.
  3. getThe parameters passed in the URL are limited in length, andpostNo,
  4. getthanpostEven less secure, because the parameters are directly exposed in the URL, they cannot be used to pass sensitive information.postEasy to prevent CSRF
  5. getThe request parameters are kept intact in the browsing history, andpostParameters in are not preserved.
  6. getThe request can only be URL encoded, andpostSupport a variety of coding methods
  7. getThe request will be actively cached by the browser, andpostManually, unless not.
  8. getGenerate a TCP packet;postTwo TCP packets are generated.

For the get method, thehttp headeranddataSend it together, and the server responds200(return data); for post, the browser sends it firstheader, server response100 continue, the browser sends againdata, server response200 ok(return data).


The options request is designed tosend outone kind“Probe” request to determineWhat must a request for a destination address haveconstraint(for example, what kind of HTTP method should be used and the custom request header) and thenSend the real request according to its constraints。 For example, the HTTP method for preflight requests of “cross domain resources” is options.

The corresponding status code is:204.

HTTP status code

  • 1xx: indicates a notification message. Indicates that the request has been received and continues processing
  • 2xx: indicates success. Indicates that the request has been successfully received

    • 200Request completed successfully
    • 204: when you only need to know the success or failure of the response, 204 can be used instead of 200 to reduce redundant data transmission.
  • 3xx: indicates redirection.

    • 301: permanent redirection. The requested page has been moved to the new URL
    • 302: temporary redirection. The requested page has been temporarily moved to the new URL
    • 304: the request is redirected to the client local cache.
  • 4xx: indicates a client error. The request has a syntax error or the request cannot be implemented

    • 400: syntax error in client request.
    • 401: client request is not authorized.
    • 403: the client’s request was rejected by the server.
    • 404: the URL requested by the client does not exist on the server side.
  • 5xxIndicates a server error. The server failed to implement a legitimate request

    • 500: server permanent error.

The difference between 301 and 302
After the implementation of 301, the new website completely inherits the old website, and the ranking of the old website is completely cleared;
After the implementation of 302, the old website will not be affected, but the new website will not be ranked.

HTTP header information

HTTP class

Common request header


Set the MIME type of the request body (for post and put requests)

The default is text / plain. The submit form must be set to:

Content-Type: application/x-www-form-urlencoded;

When using the form to upload a file:

Content-Type: multipart/form-data;



Using in nodejsbody-parserParse the post request body.
Examples of use:

let bodyParser = require('koa-bodyparser');

cookie:Set HTTP cookies sent by the server using set cookies

Cache related (negotiation cache)

  • If-Modified-Since      

This value is the last modify previously returned by the server. Allow the server to return 304 not modified.

  • If-None-Match

This value is the Etag returned by the server before.

The server judges whether the cache is hit or not according to the if modified since and if none match values sent by the browser.

Common response header

Content-Type: sets the MIME type of the response body

Set-Cookie : set HTTP cookie

Status: set HTTP response status

Cache dependency

Strong cache

Set the expiration time of the response volume cache. Before this time, the cache is hit.

  • Expires: absolute time
  • Cache control: relative time

Negotiation cache

  • Last-Modify

When the browser requests a resource for the first time, last modify will be added to the header returned by the server to identify the last modification time of the resource. If the cache is hit, 304 is returned, and no resource content is returned, and last modify is not returned.

  • ETag

Etag can ensure that each resource is unique, and resource changes will lead to Etag changes. Even if this Etag doesn’t change from the previous one. The Etag will still be returned in the header returned by the server.

HTTP protocol version

HTTP 1.x/0.9

HTTP 0.9

Only supportedGETRequest, the server can only respond to HTML format strings.

HTTP 1.0

increasePOST,HEAD。 Non persistent connection
HTTP 1.0 requiresKeep-Aliveheader

HTTP 1.1 (current application)

increasePUTPATCHOPTIONSDELETE。 The connection can be persisted

HTTP 2.0 (latest)


Http / 2 (Hypertext Transfer Protocol version 2, originally named http2.0), is the second major version of the HTTP protocol. It is mainly based on spdy protocol.

Spdy protocol
Spdy (speed, meaning “faster”). It is an application layer protocol based on TCP protocol developed by Google. The goal is to optimize the performance of HTTP protocol, shorten the loading time and improve the security of web pages by compression, multiplexing and priority technology. The core idea of spdy protocol is to minimize the number of TCP connections. Spdy is not a protocol used to replace HTTP, but an enhancement of HTTP protocol.


Binary transmission, multiplexing, header compression, the server can actively send resources to the client, more secure.

Disadvantages of http1. X

  1. There are many defects in text-based data transmission.
  2. The pipelining technology used in http / 1.1 can only handle part of the request concurrency, and still existsTeam head blocking problemTherefore, when clients need to make multiple requests, they usually establish multiple connections to reduce the delay.
  3. Request message and response messageLarge redundancy of the first message
  4. Data not compressed, resulting in a large amount of data transmission.
  5. One way request, can only be initiated by the client.

Compare how much faster http2.0 is than http1. X. Link address

Features of http2.0

Binary transfer (core)

Http2.0 introduces a new coding mechanism, which adds a new encoding mechanism between the application layer (http2.0) and the transport layer (TCP or UDP)Binary framing layer。 In the binary framing layer, all the transmitted information is divided into smaller messages and frames and encoded in binary format. amongHTTP1.xThe first message of is encapsulated in theHeaders frame, andRequest BodyPackage toData frame


In http1.0, because the browser limits the number of requests under the same domain name, when the page needs to request many resources,Team leader blockedWhen the maximum request is reached, the resource needs to wait for other resource requests to complete before sending.
Transmission in HTTP 2.0 is based on binary frames. Each TCP connection carries multiple two-way flows. Each flow has a unique identifier and priority, and the stream is composed of binary frames. The header information of the binary frame will identify which stream it belongs to, so these frames can be interleaved and then assembled into complete data through the information of frame header at the receiving end. That’s itTeam leader blockedAt the same time, it also improves the utilization of network speed.

Head compression

In http1.0, we use the form of text to transmit the header. If we carry a cookie in the header, we need to repeatedly transmit hundreds to thousands of bytes each time, which is a big expense.
In HTTP 2.0, we usedHPACK(http2 header compression algorithm) the compressed format encodes the transmitted header and reduces the size of the header. And maintained at both endsIndex table, which is used to record the existing header. The key name of the recorded header can be transmitted later in the transmission process. After receiving the data, the opposite end can find the corresponding value through the key name.

Server push

By using the push technology of the server and pushing the necessary resources to the client in advance, the delay time can be reduced. Prefetch can also be used when browsers are compatible.

More secure

HTTP 2.0 usesTLSThe development ofALPNAs a protocol upgrade, in addition, http2.0TLSThrough blacklist mechanism, hundreds of no longer secure encryption algorithms are disabled.


HTTPSIt’s safeHTTPHTTPThe content of the protocol is plaintext transmission,HTTPSThe purpose is to encrypt these contents and ensure the security of information transmission. The last letter S refers toSSL/TLSProtocol, which lies between HTTP protocol and TCP / IP protocol.
HTTP default port number: 80. HTTPS default port number: 443

Features of HTTPS:

Content encryption: using hybrid encryption technology, the middleman can not directly view the plaintext content
Authentication: the client accesses its own server through certificate authentication
Protect data integrity: to prevent the transmission content from being impersonated or tampered with by the middleman

The process of establishing an HTTPS connection

  • When using HTTPS, it is necessary to ensure that the server has correctly configured the corresponding security certificate
  • The client sends the request to the server
  • The server returns the public key and certificate to the client
  • After receiving the certificate, the client will verify the security of the certificate. If it passes, it will generate a random number randomly, encrypt it with the public key, and send it to the server
  • After receiving the encrypted random number, the server will decrypt it with the private key to get the real random number, and then use the random number as the private key to encrypt the data to be sent symmetrically
  • After receiving the encrypted data, the client decrypts the data using the private key (i.e., the generated random value) and parses the data to present the results to the client
  • SSL encryption establishment

HTTP class