fork download
  1. #include <curl/curl.h>
  2. #include <iostream>
  3. #include <string>
  4.  
  5. // Callback function to capture the response.
  6. static size_t WriteCallback(void* contents, size_t size, size_t nmemb, void* userp)
  7. {
  8. ((std::string*)userp)->append((char*)contents, size * nmemb);
  9. return size * nmemb;
  10. }
  11.  
  12. int main() {
  13. CURL *curl;
  14. CURLcode res;
  15. std::string readBuffer;
  16.  
  17. curl = curl_easy_init();
  18. if(curl) {
  19. const char* postData = "{\"text\": \"Hello, world!\"}";
  20.  
  21. // Set URL for the POST request.
  22. curl_easy_setopt(curl, CURLOPT_URL, "http://localhost:5000/echo");
  23. curl_easy_setopt(curl, CURLOPT_POSTFIELDS, postData);
  24.  
  25. struct curl_slist *headers = NULL;
  26. headers = curl_slist_append(headers, "Content-Type: application/json");
  27. curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
  28.  
  29. curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback);
  30. curl_easy_setopt(curl, CURLOPT_WRITEDATA, &readBuffer);
  31.  
  32. res = curl_easy_perform(curl);
  33. if(res != CURLE_OK) {
  34. std::cerr << "curl_easy_perform() failed: " << curl_easy_strerror(res) << "\n";
  35. } else {
  36. std::cout << "Response: " << readBuffer << "\n";
  37. }
  38. curl_easy_cleanup(curl);
  39. curl_slist_free_all(headers);
  40. }
  41. return 0;
  42. }
  43.  
Success #stdin #stdout 0.03s 25764KB
stdin
Standard input is empty
stdout
#include <curl/curl.h>
#include <iostream>
#include <string>

// Callback function to capture the response.
static size_t WriteCallback(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) {
        const char* postData = "{\"text\": \"Hello, world!\"}";

        // Set URL for the POST request.
        curl_easy_setopt(curl, CURLOPT_URL, "http://localhost:5000/echo");
        curl_easy_setopt(curl, CURLOPT_POSTFIELDS, postData);

        struct curl_slist *headers = NULL;
        headers = curl_slist_append(headers, "Content-Type: application/json");
        curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);

        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback);
        curl_easy_setopt(curl, CURLOPT_WRITEDATA, &readBuffer);

        res = curl_easy_perform(curl);
        if(res != CURLE_OK) {
            std::cerr << "curl_easy_perform() failed: " << curl_easy_strerror(res) << "\n";
        } else {
            std::cout << "Response: " << readBuffer << "\n";
        }
        curl_easy_cleanup(curl);
        curl_slist_free_all(headers);
    }
    return 0;
}