Creating a simple C++ program that performs a HTTP GET request to retrieve content from a URL can be achieved using various libraries. One of the most popular and easy-to-use libraries for handling HTTP requests in C++ is libcurl. Here's how you can do it:
1. Ensure libcurl is Installed
First, you need to have libcurl installed on your development machine. The installation process varies depending on your operating system.
-
On Ubuntu/Debian:
sudo apt-get update
sudo apt-get install libcurl4-openssl-dev
-
On CentOS/Fedora:
sudo yum install libcurl-devel
-
On Windows:
Installing libcurl on Windows might be a bit more involved. You can download pre-built binaries or use vcpkg or a similar package manager to install it.
2. Example Code
Below is a simple C++ program named HttpGet.cpp that performs a GET request and prints the content of the specified URL.
#include <iostream>
#include <curl/curl.h>
// This function will be used to write the response data
size_t WriteCallback(void *contents, size_t size, size_t nmemb, std::string *userp) {
userp->append((char*)contents, size * nmemb);
return size * nmemb;
}
int main() {
CURL *curl;
CURLcode res;
std::string readBuffer; // This will hold the fetched URL content
curl = curl_easy_init();
if(curl) {
curl_easy_setopt(curl, CURLOPT_URL, "http://example.com");
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &readBuffer);
// Perform the request, and store the result code
res = curl_easy_perform(curl);
// Check for errors
if(res != CURLE_OK) {
std::cerr << "curl_easy_perform() failed: " << curl_easy_strerror(res) << std::endl;
} else {
// On success, print the content
std::cout << readBuffer << std::endl;
}
// Always cleanup
curl_easy_cleanup(curl);
}
return 0;
}
3. Compiling the Program
To compile the program, you need to link it against libcurl. Here's how you can do it:
-
On Linux:
g++ -o HttpGet HttpGet.cpp -lcurl
-
On Windows:
Compiling on Windows requires specifying the path to the libcurl libraries and headers, which depends on how you installed libcurl.
4. Running Your Program
Execute your program:
./HttpGet
This program will fetch and display the content from "http://example.com". You can replace the URL with any other URL of your choice to fetch different content.
Note:
This example is a basic demonstration. Real-world applications might need to handle HTTPS, redirects, error handling, and other HTTP features more robustly. Libcurl offers extensive options and features for these kinds of requirements.