乐闻世界logo
搜索文章和话题

How do you make a HTTP request with C++?

1个答案

1

Making HTTP requests in C++ typically requires third-party libraries, as the standard C++ library lacks direct support for network programming. The following sections introduce two popular libraries: C++ REST SDK (also known as Casablanca) and cURL, to demonstrate how to make HTTP requests in C++.

1. Using C++ REST SDK (Casablanca)

C++ REST SDK is a Microsoft-maintained project designed to simplify HTTP client and server programming. Below is a basic example of using C++ REST SDK to perform an HTTP GET request:

First, install the C++ REST SDK. If you are using Visual Studio, you can install it via the NuGet package manager.

cpp
#include <cpprest/http_client.h> #include <cpprest/filestream.h> #include <iostream> using namespace utility; // Common utilities like string conversions using namespace web; // Common features like URIs. using namespace web::http; // Common HTTP functionality using namespace web::http::client; // HTTP client features using namespace concurrency::streams; // Asynchronous streams int main() { // Create HTTP client object http_client client(U("http://example.com")); // Build request uri_builder builder(U("/api/data")); builder.append_query(U("key"), U("value")); // Send GET request client.request(methods::GET, builder.to_string()) .then([](http_response response) { // Check response status code if (response.status_code() == status_codes::OK) { return response.extract_string(); } return pplx::task_from_result(utility::string_t()); }) .then([](const utility::string_t& body) { std::wcout << body << std::endl; }) .wait(); return 0; }

2. Using cURL

cURL is a powerful library for handling URLs, supporting multiple protocols including HTTP and HTTPS. An example of using cURL for HTTP requests is shown below:

First, ensure the cURL library is installed on your system.

cpp
#include <curl/curl.h> #include <iostream> size_t write_callback(void *contents, size_t size, size_t nmemb, void *userp) { ((std::string*)userp)->append((char*)contents, size * nmemb); return size * nmemb; } int main() { CURL *curl; CURLcode res; std::string readBuffer; curl = curl_easy_init(); if(curl) { curl_easy_setopt(curl, CURLOPT_URL, "http://example.com/api/data?key=value"); curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_callback); curl_easy_setopt(curl, CURLOPT_WRITEDATA, &readBuffer); res = curl_easy_perform(curl); if(res != CURLE_OK) { fprintf(stderr, "curl_easy_perform() failed: %s\n", curl_easy_strerror(res)); } else { std::cout << readBuffer << std::endl; } curl_easy_cleanup(curl); } return 0; }

Both approaches are effective for making HTTP requests in C++. The choice of library depends on project requirements: C++ REST SDK offers a modern, asynchronous API, while cURL is valued for its stability and broad protocol support.

2024年7月4日 10:41 回复

你的答案