HTTP Request and Response
HTTP (Hypertext Transfer Protocol) is an application layer protocol which is used for transmitting data over the internet. It follows a client-server model, where the client sends a request to the server and the server sends back a response.
HTTP Request
An HTTP request is a message sent by a client to a server to initiate a request for a particular resource. It consists of four parts:
- Request line: It consists of the HTTP method, the URL, and the HTTP version. For example, GET /index.html HTTP/1.1
- Header fields: It consists of key-value pairs which provide additional information about the request. For example, Accept-Language: en-US
- Request body: It is optional and contains data that needs to be sent along with the request. For example, form data or file uploads.
- Request method: It specifies the HTTP method that should be used for the request. The most common methods are GET, POST, PUT and DELETE.
The following is an example of an HTTP request:
GET /index.html HTTP/1.1
Host: www.example.com
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Connection: keep-alive
Upgrade-Insecure-Requests: 1
HTTP Response
An HTTP response is a message sent by a server to a client in response to a request sent by the client. It consists of three parts:
- Status line: It consists of the HTTP version, the status code, and the reason phrase. For example, HTTP/1.1 200 OK
- Header fields: It consists of key-value pairs which provide additional information about the response. For example, Content-Type: text/html
- Response body: It contains the data that was requested by the client. For example, HTML, JSON or XML data.
The following is an example of an HTTP response:
HTTP/1.1 200 OK
Date: Sat, 05 Jun 2021 12:00:00 GMT
Server: Apache/2.4.38 (Unix)
Content-Type: text/html; charset=utf-8
Content-Length: 1234
Connection: keep-alive
<!DOCTYPE html>
<html>
<head>
<title>Example Page</title>
</head>
<body>
<h1>Welcome to Example Page</h1>
</body>
</html>
In summary, HTTP request and response work by following a client-server model where the client sends a request to the server and the server sends back a response. The request consists of a request line, header fields, request body, and request method while the response consists of a status line, header fields, and response body.