HTTP client
- C++ course
- Advanced
- Lesson 59/83
- 5 min
Learn to write a simple HTTP client.
What is HTTP?
HTTP (HyperText Transfer Protocol) is a text based protocol for client server communication on the web. It is built on top of TCP. A client sends a request, the server returns a response. Requests start with a method: GET, POST, PUT, DELETE.
Example of a GET request: GET / HTTP/1.1\r\nHost: example.com\r\n\r\n. The first line is the request line (method, path, version). Then come headers, each ending with \r\n. An empty line (\r\n\r\n) marks the end of headers. The response is similar: HTTP/1.1 200 OK\r\n.... This lesson covers building the request string.
Building the request string
An HTTP GET request is built as a string and sent over a TCP socket. It consists of a request line, headers and an empty line. The Host header is mandatory in HTTP/1.1; it carries the server name.
Example: std::string host = "example.com"; std::string request = "GET / HTTP/1.1\r\nHost: " + host + "\r\nConnection: close\r\n\r\n";. Here Connection: close asks the server to close the connection after the response. The built string is written to the socket with send(sock, request.c_str(), request.size(), 0). To read the response you use recv. This lesson focuses on building the string; real sending comes in later projects.
Practice Build an HTTP GET request
Define std::string host = "example.com";. Build a std::string request: start with "GET / HTTP/1.1\r\nHost: ", add + host +, end with "\r\nConnection: close\r\n\r\n". Print std::cout << "Request ready";.
Starter code
#include <iostream>
#include <string>
// Build an HTTP GET request string
int main() {
// Build the request string and print the status
return 0;
}Sample solution
#include <iostream>
#include <string>
int main() {
std::string host = "example.com";
std::string request = "GET / HTTP/1.1\r\nHost: " + host + "\r\nConnection: close\r\n\r\n";
std::cout << "Request ready";
return 0;
}Expected output
Request ready
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match each piece to its role
| Term | Meaning |
|---|---|
GET |
Read data method |
POST |
Send data method |
Host: |
Server name header |
\r\n\r\n |
End of headers |
2 Complete the GET method
std::string request = "____ / HTTP/1.1\r
Host: " + host + "\r
Connection: close\r
\r
";
std::string request = "GET / HTTP/1.1\r
Host: " + host + "\r
Connection: close\r
\r
";
Explanation: GET is the method for reading data.
3 Why is the Host header required?
- To speed up the connection
- So the server can find the right site Correct answer
- To compress the response
- To encrypt the request
Explanation: The Host header tells the server which site to respond for.