Mark As Completed Discussion

Using HTTP in C++

When working with external APIs, the HTTP protocol is commonly used for making requests and receiving responses. In C++, you can utilize the cURL library to handle HTTP requests.

To make an HTTP request in C++ using cURL, you need to follow these steps:

  1. Include the necessary header file for cURL:

    TEXT/X-C++SRC
    1#include <curl/curl.h>
  2. Create a callback function to handle the response data:

    TEXT/X-C++SRC
    1size_t WriteCallback(char* content, size_t size, size_t nmemb, std::string* response) {
    2  size_t total_size = size * nmemb;
    3  response->append(content, total_size);
    4  return total_size;
    5}
  3. Initialize a cURL handle:

    TEXT/X-C++SRC
    1CURL* curl = curl_easy_init();
  4. Set the URL of the API endpoint:

    TEXT/X-C++SRC
    1curl_easy_setopt(curl, CURLOPT_URL, "https://api.example.com/data");
  5. Set the callback function for writing the response data:

    TEXT/X-C++SRC
    1curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback);
  6. Set the response string as the callback data:

    TEXT/X-C++SRC
    1std::string response;
    2curl_easy_setopt(curl, CURLOPT_WRITEDATA, &response);
  7. Perform the API request:

    TEXT/X-C++SRC
    1CURLcode res = curl_easy_perform(curl);
  8. Check the response and handle any errors:

    TEXT/X-C++SRC
    1if (res == CURLE_OK) {
    2  // Request succeeded
    3} else {
    4  // Request failed
    5}
  9. Cleanup the cURL handle:

    TEXT/X-C++SRC
    1curl_easy_cleanup(curl);

Here's an example of making an HTTP request using cURL in C++:

TEXT/X-C++SRC
1#include <iostream>
2#include <curl/curl.h>
3
4size_t WriteCallback(char* content, size_t size, size_t nmemb, std::string* response) {
5  size_t total_size = size * nmemb;
6  response->append(content, total_size);
7  return total_size;
8}
9
10int main() {
11  CURL* curl = curl_easy_init();
12  if (curl) {
13    std::string response;
14
15    // Set the URL
16    curl_easy_setopt(curl, CURLOPT_URL, "https://api.example.com/data");
17
18    // Set the callback function for writing response
19    curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback);
20
21    // Set the response string as the callback data
22    curl_easy_setopt(curl, CURLOPT_WRITEDATA, &response);
23
24    // Perform the API request
25    CURLcode res = curl_easy_perform(curl);
26
27    if (res == CURLE_OK) {
28      // Request succeeded
29      std::cout << "API request succeeded" << std::endl;
30      std::cout << "Response: " << response << std::endl;
31    } else {
32      // Request failed
33      std::cerr << "API request failed: " << curl_easy_strerror(res) << std::endl;
34    }
35
36    // Cleanup the CURL handle
37    curl_easy_cleanup(curl);
38  }
39
40  return 0;
41}
CPP
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment