Mark As Completed Discussion

To make HTTP requests in C++, you can use a library like libcurl, which provides an easy-to-use interface for performing HTTP requests and handling responses. Here's an example of how to make a GET request using libcurl:

TEXT/X-C++SRC
1#include <iostream>
2#include <curl/curl.h>
3
4// Function to write response data
5size_t WriteCallback(void* contents, size_t size, size_t nmemb, std::string* output) {
6    size_t totalSize = size * nmemb;
7    output->append((char*)contents, totalSize);
8    return totalSize;
9}
10
11int main() {
12    CURL* curl;
13    CURLcode res;
14
15    // Initialize CURL
16    curl_global_init(CURL_GLOBAL_DEFAULT);
17    curl = curl_easy_init();
18
19    if (curl) {
20        std::string response;
21
22        // Set URL for the request
23        curl_easy_setopt(curl, CURLOPT_URL, "https://jsonplaceholder.typicode.com/posts/1");
24
25        // Set response callback function
26        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback);
27
28        // Pass response data to the callback function
29        curl_easy_setopt(curl, CURLOPT_WRITEDATA, &response);
30
31        // Perform the request
32        res = curl_easy_perform(curl);
33
34        // Check for errors
35        if (res != CURLE_OK) {
36            std::cerr << "Failed to perform request: " << curl_easy_strerror(res) << std::endl;
37        }
38        else {
39            // Print the response
40            std::cout << response << std::endl;
41        }
42
43        // Cleanup CURL
44        curl_easy_cleanup(curl);
45    }
46
47    // Cleanup CURL global state
48    curl_global_cleanup();
49
50    return 0;
51}
CPP
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment