Http Client in C++
Here’s the translation of the Go HTTP client example to C++, formatted in Markdown suitable for Hugo:
The C++ standard library doesn’t come with built-in HTTP client functionality, so we’ll use the popular libcurl
library for this example. Make sure you have libcurl
installed and properly linked to your project.
#include <iostream>
#include <curl/curl.h>
#include <sstream>
#include <string>
// Callback function to handle the response
size_t WriteCallback(void* contents, size_t size, size_t nmemb, std::string* output) {
size_t total_size = size * nmemb;
output->append((char*)contents, total_size);
return total_size;
}
int main() {
// Initialize libcurl
CURL* curl = curl_easy_init();
if (!curl) {
std::cerr << "Failed to initialize libcurl" << std::endl;
return 1;
}
// Set the URL
curl_easy_setopt(curl, CURLOPT_URL, "https://gobyexample.com");
// Set up the response handling
std::string response_string;
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &response_string);
// Perform the request
CURLcode res = curl_easy_perform(curl);
if (res != CURLE_OK) {
std::cerr << "curl_easy_perform() failed: " << curl_easy_strerror(res) << std::endl;
curl_easy_cleanup(curl);
return 1;
}
// Get the response status
long response_code;
curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &response_code);
std::cout << "Response status: " << response_code << std::endl;
// Print the first 5 lines of the response body
std::istringstream response_stream(response_string);
std::string line;
for (int i = 0; i < 5 && std::getline(response_stream, line); ++i) {
std::cout << line << std::endl;
}
// Clean up
curl_easy_cleanup(curl);
return 0;
}
This C++ program uses libcurl
to issue an HTTP GET request to a server. Here’s a breakdown of what the code does:
We include the necessary headers, including
curl/curl.h
forlibcurl
.We define a
WriteCallback
function thatlibcurl
will use to handle the response data.In the
main
function, we initializelibcurl
withcurl_easy_init()
.We set the URL for the request using
curl_easy_setopt()
.We set up the response handling by specifying our
WriteCallback
function and a string to store the response.We perform the request with
curl_easy_perform()
.After the request, we retrieve the response status code using
curl_easy_getinfo()
.We then print the response status and the first 5 lines of the response body.
Finally, we clean up the
libcurl
resources withcurl_easy_cleanup()
.
To compile and run this program, you’ll need to link against libcurl
. For example:
$ g++ -o http_client http_client.cpp -lcurl
$ ./http_client
Response status: 200
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Go by Example</title>
This example demonstrates how to make HTTP requests in C++ using libcurl
, which provides functionality similar to the net/http
package in other languages.