### Install cpr using vcpkg Source: https://github.com/libcpr/docs/blob/main/index.md Use vcpkg to download and install the cpr library. Ensure vcpkg is integrated with your system. ```bash git clone https://github.com/Microsoft/vcpkg.git cd vcpkg ./bootstrap-vcpkg.sh ./vcpkg integrate install ./vcpkg install cpr ``` -------------------------------- ### Asynchronous GET, POST, and Batch Requests Source: https://context7.com/libcpr/docs/llms.txt Demonstrates single and batched asynchronous GET requests, as well as cancellable MultiPostAsync requests. Use `GetAsync` for single operations and `MultiPostAsync` for parallel processing with cancellation. ```cpp #include #include #include #include int main() { // Single async GET cpr::AsyncResponse fr = cpr::GetAsync(cpr::Url{"http://www.httpbin.org/get"}); fr.wait(); std::cout << fr.get().text << std::endl; // Batch of 10 parallel GETs std::vector batch; for (int i = 0; i < 10; ++i) { batch.emplace_back(cpr::GetAsync( cpr::Url{"http://www.httpbin.org/get"}, cpr::Parameters{{"i", std::to_string(i)}} )); } for (auto& ar : batch) { std::cout << ar.get().status_code << std::endl; // 200 } // Cancellable MultiPostAsync using AsyncResC = cpr::AsyncWrapper; cpr::Url post_url{"http://www.httpbin.org/post"}; std::vector responses{cpr::MultiPostAsync( std::tuple{post_url, cpr::Payload{{"name", "Alice"}}}, std::tuple{post_url, cpr::Payload{{"role", "admin"}}} )}; // Cancel all if first doesn't finish within 10ms if (responses[0].wait_for(std::chrono::milliseconds(10)) == std::future_status::timeout) { for (auto& res : responses) res.Cancel(); } } ``` -------------------------------- ### Perform HTTP Range Request with Empty Start Source: https://github.com/libcpr/docs/blob/main/advanced-usage.md Use `std::nullopt` with `cpr::Range` to specify a range that starts from the beginning of the resource up to a specified byte. This example requests the last 5 bytes. ```c++ cpr::Response r = cpr::Get(cpr::Url{"http://www.httpbin.org/headers"}, cpr::Range{std::nullopt, 5}); std::cout << r.text << std::endl; /* * { * "headers": { * "Range": "bytes=-5", * ... * } * } */ ``` -------------------------------- ### Perform Multiple GET Requests with Timeout in C++ Source: https://github.com/libcpr/docs/blob/main/advanced-usage.md Utilize the convenience function MultiGet to perform multiple HTTP GET requests. This example demonstrates setting a timeout for one of the requests and specifying the number of sessions to be created internally. ```c++ // Performs two HTTP Get requests to https://www.httpbin.org/get, where the first one has an additional timeout option set. // The number of parameter tuples specifies the number of sessions which will be internally created std::vector responses = MultiGet(std::tuple{Url{"https://www.httpbin.org/get"}, Timeout{1000}}, std::tuple{Url{"https://www.httpbin.org/get"}}); ``` -------------------------------- ### Perform a GET Request with C++ Requests Source: https://github.com/libcpr/docs/blob/main/index.md Demonstrates a basic GET request to fetch contributors from a GitHub API. Includes setting URL, authentication, and parameters. Accesses response status code, headers, and text content. ```c++ #include int main(int argc, char** argv) { cpr::Response r = cpr::Get(cpr::Url{"https://api.github.com/repos/libcpr/cpr/contributors"}, cpr::Authentication{"user", "pass", cpr::AuthMode::BASIC}, cpr::Parameters{{"anon", "true"}, {"key", "value"}}); r.status_code; // 200 r.header["content-type"]; // application/json; charset=utf-8 r.text; // JSON text string } ``` -------------------------------- ### Build and Install C++ Requests with CMake (System Curl) Source: https://github.com/libcpr/docs/blob/main/index.md Builds and installs C++ Requests using CMake, with the option to use the system's libcurl by setting `CPR_USE_SYSTEM_CURL=ON`. This is a prerequisite for using `find_package` integration. ```bash git clone https://github.com/libcpr/cpr.git cd cpr && mkdir build && cd build cmake .. -DCPR_USE_SYSTEM_CURL=ON cmake --build . --parallel sudo cmake --install . ``` -------------------------------- ### GET Request with Multiple Parameters Source: https://github.com/libcpr/docs/blob/main/introduction.md Include multiple key-value pairs as URL parameters in a GET request. Parameters can be constructed inline or declared separately. ```c++ // Constructing it in place cpr::Response r = cpr::Get(cpr::Url{"http://www.httpbin.org/get"}, cpr::Parameters{{"hello", "world"}, {"stay", "cool"}}); std::cout << r.url << std::endl; // http://www.httpbin.org/get?hello=world&stay=cool std::cout << r.text << std::endl; /* * { * "args": { * "hello": "world" * "stay": "cool" * }, * "headers": { * .. * }, * "url": "http://httpbin.org/get?hello=world&stay=cool" * } */ ``` ```c++ // Constructing it outside cpr::Parameters parameters = cpr::Parameters{{"hello", "world"}, {"stay", "cool"}}; cpr::Response r_outside = cpr::Get(cpr::Url{"http://www.httpbin.org/get"}, parameters); std::cout << r_outside.url << std::endl; // http://www.httpbin.org/get?hello=world&stay=cool std::cout << r_outside.text << std::endl; // Same text response as above ``` -------------------------------- ### Basic Asynchronous GET Request Source: https://github.com/libcpr/docs/blob/main/advanced-usage.md Demonstrates how to initiate an asynchronous GET request and retrieve the response later. The `GetAsync` function returns an `AsyncResponse` object that can be used to wait for and get the final `Response`. ```APIDOC ## Basic Asynchronous GET Request Initiate an asynchronous GET request and retrieve the response later. The `GetAsync` function returns an `AsyncResponse` object that can be used to wait for and get the final `Response`. ### Method Signature ```c++ cpr::AsyncResponse cpr::GetAsync(const Url& url, const Parameters& parameters = Parameters{}); ``` ### Example ```c++ AsyncResponse fr = cpr::GetAsync(cpr::Url{"http://www.httpbin.org/get"}); // Sometime later... cpr::Response r = fr.get(); // This blocks until the request is complete std::cout << r.text << std::endl; ``` ``` -------------------------------- ### Asynchronous Requests Source: https://context7.com/libcpr/docs/llms.txt Demonstrates how to perform asynchronous HTTP GET and POST requests using cpr::GetAsync, cpr::PostAsync, and cpr::MultiPostAsync. It also shows how to batch requests and handle cancellation. ```APIDOC ## Asynchronous Requests `cpr::GetAsync` / `PostAsync` / etc. return `cpr::AsyncWrapper`, which mirrors `std::future`. Multiple async requests can be batched in a container and awaited independently. `MultiGetAsync` / `MultiPostAsync` bundle requests with thread-pool parallelism and optional per-request cancellation. ```cpp #include #include #include #include int main() { // Single async GET cpr::AsyncResponse fr = cpr::GetAsync(cpr::Url{"http://www.httpbin.org/get"}); fr.wait(); std::cout << fr.get().text << std::endl; // Batch of 10 parallel GETs std::vector batch; for (int i = 0; i < 10; ++i) { batch.emplace_back(cpr::GetAsync( cpr::Url{"http://www.httpbin.org/get"}, cpr::Parameters{{"i", std::to_string(i)}} )); } for (auto& ar : batch) { std::cout << ar.get().status_code << std::endl; // 200 } // Cancellable MultiPostAsync using AsyncResC = cpr::AsyncWrapper; cpr::Url post_url{"http://www.httpbin.org/post"}; std::vector responses{cpr::MultiPostAsync( std::tuple{post_url, cpr::Payload{{"name", "Alice"}}}, std::tuple{post_url, cpr::Payload{{"role", "admin"}}} )}; // Cancel all if first doesn't finish within 10ms if (responses[0].wait_for(std::chrono::milliseconds(10)) == std::future_status::timeout) { for (auto& res : responses) res.Cancel(); } } ``` ``` -------------------------------- ### Make an Asynchronous GET Request Source: https://github.com/libcpr/docs/blob/main/advanced-usage.md Initiates an asynchronous GET request. The `get()` method blocks until the request is complete. ```c++ AsyncResponse fr = cpr::GetAsync(cpr::Url{"http://www.httpbin.org/get"}); // Sometime later... cpr::Response r = fr.get(); // This blocks until the request is complete std::cout << r.text << std::endl; ``` -------------------------------- ### Add cpr as a dependency in Meson Source: https://github.com/libcpr/docs/blob/main/index.md Configure the meson.build file to include cpr as a dependency for your C++ project. This example assumes cpr is installed via 'meson wrap install cpr'. ```conf project('cpr-test', 'cpp', version : '0.1', default_options : ['warning_level=3', 'cpp_std=c++17']) cpr_dep = dependency('cpr') exe = executable('cpr-test', 'cpr_test.cpp', dependencies: [ cpr_dep ], install: true) test('basic', exe) ``` -------------------------------- ### Configuring HTTP Compression with cpr::AcceptEncoding Source: https://context7.com/libcpr/docs/llms.txt Shows how to control the Accept-Encoding header for HTTP compression. Examples include specifying explicit encoding schemes (deflate, gzip, zlib), using string-based encoding names, letting libcurl decide, and disabling the header entirely. ```cpp #include #include int main() { // Explicit encoding schemes cpr::Response r1 = cpr::Get( cpr::Url{"http://www.httpbin.org/get"}, cpr::AcceptEncoding{{ cpr::AcceptEncodingMethods::deflate, cpr::AcceptEncodingMethods::gzip, cpr::AcceptEncodingMethods::zlib }} ); // String-based cpr::Response r2 = cpr::Get( cpr::Url{"http://www.httpbin.org/get"}, cpr::AcceptEncoding{{"deflate", "gzip"}} ); // Let libcurl decide (default behavior) cpr::Response r3 = cpr::Get( cpr::Url{"http://www.httpbin.org/get"}, cpr::AcceptEncoding{} ); // Disable Accept-Encoding header entirely cpr::Session session; session.SetUrl(cpr::Url{"https://example.com"}); session.SetAcceptEncoding({cpr::AcceptEncodingMethods::disabled}); cpr::Response r4 = session.Get(); } ``` -------------------------------- ### Basic GET Request with cpr Source: https://github.com/libcpr/docs/blob/main/introduction.md Make a simple GET request to a URL. Ensure the cpr header is included in your project's include path. ```c++ #include // Make sure this header is available in your include path // Somewhere else cpr::Response r = cpr::Get(cpr::Url{"http://www.httpbin.org/get"}); ``` -------------------------------- ### Integrate CPR with CMake using FetchContent in CMakeLists.txt Source: https://context7.com/libcpr/docs/llms.txt Use CMake's FetchContent module to automatically download and build CPR, including its dependency libcurl. This simplifies project setup for C++ applications. ```cmake # CMakeLists.txt cmake_minimum_required(VERSION 3.14) project(my_app CXX) set(CMAKE_CXX_STANDARD 17) include(FetchContent) FetchContent_Declare( cpr GIT_REPOSITORY https://github.com/libcpr/cpr.git GIT_TAG 1.12.0 ) FetchContent_MakeAvailable(cpr) add_executable(my_app main.cpp) target_link_libraries(my_app PRIVATE cpr::cpr) ``` -------------------------------- ### Send Cookies in a Request Source: https://github.com/libcpr/docs/blob/main/advanced-usage.md Sends a GET request and then another GET request including the cookies received from the first response. Demonstrates how to persist cookies between requests. ```c++ cpr::Response r = cpr::Get(cpr::Url{"http://www.httpbin.org/cookies/set?cookies=yummy"}); cpr::Response another_r = cpr::Get(cpr::Url{"http://www.httpbin.org/cookies"}, r.cookies); std::cout << another_r.text << std::endl; /* * { * "cookies": { * "cookie": "yummy" * } * } */ ``` -------------------------------- ### HTTP Methods (PUT, PATCH, DELETE, HEAD, OPTIONS) in CPR Source: https://context7.com/libcpr/docs/llms.txt Shows how to use PUT, PATCH, DELETE, HEAD, and OPTIONS requests with CPR. Includes examples of asynchronous and callback variants for DELETE and HEAD requests. ```cpp #include #include #include int main() { // PUT cpr::Response put_r = cpr::Put( cpr::Url{"http://www.httpbin.org/put"}, cpr::Payload{{"key", "value"}} ); assert(put_r.status_code == 200); // PATCH cpr::Response patch_r = cpr::Patch( cpr::Url{"http://www.httpbin.org/patch"}, cpr::Payload{{"field", "updated"}} ); // DELETE cpr::Response del_r = cpr::Delete(cpr::Url{"http://www.httpbin.org/delete"}); // HEAD (only headers, no body) cpr::Response head_r = cpr::Head(cpr::Url{"http://www.httpbin.org/get"}); std::cout << "Content-Type: " << head_r.header["content-type"] << std::endl; // OPTIONS cpr::Response opt_r = cpr::OPTIONS(cpr::Url{"http://www.httpbin.org/get"}); // Async variants — return AsyncWrapper (like std::future) cpr::AsyncResponse async_del = cpr::DeleteAsync(cpr::Url{"http://www.httpbin.org/delete"}); cpr::AsyncResponse async_head = cpr::HeadAsync(cpr::Url{"http://www.httpbin.org/get"}); std::cout << async_del.get().status_code << std::endl; // 200 std::cout << async_head.get().status_code << std::endl; // 200 // Callback variants — callback receives Response, returns any type auto cb = cpr::DeleteCallback( [](cpr::Response r) { return r.status_code; }, cpr::Url{"http://www.httpbin.org/delete"} ); std::cout << cb.get() << std::endl; // 200 } ``` -------------------------------- ### Iterating Through Response Cookies Source: https://github.com/libcpr/docs/blob/main/advanced-usage.md Example of iterating through cookies returned in a response and accessing individual cookie fields like domain, path, and name. ```c++ cpr::Response r = cpr::Get(cpr::Url{"http://www.httpbin.org/cookies/set?cookies=yummy"}); for(const auto &cookie : r.cookies) { std::cout << cookie.GetDomain() << ":"; std::cout << cookie.IsIncludingSubdomains() << ":"; std::cout << cookie.GetPath() << ":"; std::cout << cookie.IsHttpsOnly() << ":"; std::cout << cookie.GetExpiresString() << ":"; std::cout << cookie.GetName() << ":"; std::cout << cookie.GetValue() << std::endl; // For example, this will print: // www.httpbin.org:0:/:0:Thu, 01 Jan 1970 00:00:00 GMT:cookies:yummy } ``` -------------------------------- ### Integrate CPR with CMake using find_package in Bash Source: https://context7.com/libcpr/docs/llms.txt Install CPR system-wide and use CMake's find_package command. This method requires CPR to be pre-installed and can be configured to use a system libcurl. ```bash # Or install system-wide and use find_package git clone https://github.com/libcpr/cpr.git cd cpr && mkdir build && cd build cmake .. -DCPR_USE_SYSTEM_CURL=ON cmake --build . --parallel sudo cmake --install . # Then in project: # find_package(cpr REQUIRED) ``` -------------------------------- ### Get Full Request URL from Session Source: https://github.com/libcpr/docs/blob/main/advanced-usage.md Retrieve the complete URL, including any parameters, that will be used for a request before it is actually sent. This is useful for debugging or logging. ```c++ cpr::Url url = cpr::Url{"http://www.httpbin.org/get"}; cpr::Parameters parameters = cpr::Parameters{{"hello", "world"}}; cpr::Session session; session.SetUrl(url); session.SetParameters(parameters); std::string fullRequestUrl = session.GetFullRequestUrl(); std::cout << fullRequestUrl << std::endl; // Prints http://www.httpbin.org/get?hello=world ``` -------------------------------- ### Initialize a C++ project with Meson Source: https://github.com/libcpr/docs/blob/main/index.md Initialize a new C++ project using Meson. This command sets up the basic project structure with a C++ language and no subdirectories. ```bash meson init -l cpp -n cpr-test ``` -------------------------------- ### Enable All Supported HTTP Compression Methods (Default) Source: https://github.com/libcpr/docs/blob/main/advanced-usage.md Demonstrates how to configure cpr::AcceptEncoding with an empty list to enable all supported HTTP compression methods, which is the default behavior. ```c++ // An empty list of accepted encodings in combination with a direct request without any state cpr::Response r = cpr::Get(cpr::Url{"http://www.httpbin.org/get"}, cpr::AcceptEncoding{}); // An empty list of accepted encodings in combination with a stateful cpr::Session object session.SetAcceptEncoding(cpr::AcceptEncoding{}); ``` -------------------------------- ### Accessing CPR Response Data Source: https://github.com/libcpr/docs/blob/main/advanced-usage.md Example of making a GET request and accessing response data like status code, error messages, elapsed time, and body text. ```c++ cpr::Response r = cpr::Get(cpr::Url{"http://www.httpbin.org/get"}); if(r.status_code == 0) std::cerr << r.error.message << std::endl; else if (r.status_code >= 400) { std::cerr << "Error [" << r.status_code << "] making request" << std::endl; } else { std::cout << "Request took " << r.elapsed << std::endl; std::cout << "Body:" << std::endl << r.text; } ``` -------------------------------- ### Basic Server-Sent Events Usage in C++ Source: https://github.com/libcpr/docs/blob/main/sse.md Demonstrates setting up a session to receive Server-Sent Events and processing them with a callback. The callback receives event details and returns true to continue receiving. ```c++ #include #include int main() { cpr::Session session; session.SetUrl(cpr::Url{"https://example.com/events"}); // Set up SSE callback session.SetServerSentEventCallback( cpr::ServerSentEventCallback{ [](cpr::ServerSentEvent&& event, intptr_t userdata) { std::cout << "Event Type: " << event.event << std::endl; std::cout << "Data: " << event.data << std::endl; if (event.id.has_value()) { std::cout << "ID: " << event.id.value() << std::endl; } if (event.retry.has_value()) { std::cout << "Retry: " << event.retry.value() << " ms" << std::endl; } // Return true to continue receiving events, false to stop return true; } } ); cpr::Response response = session.Get(); std::cout << "Status: " << response.status_code << std::endl; return 0; } ``` -------------------------------- ### Other Request Methods (Blocking and Async) Source: https://github.com/libcpr/docs/blob/main/advanced-usage.md Demonstrates how to perform DELETE, PATCH, HEAD, and OPTIONS requests using both regular blocking calls and asynchronous calls that return an AsyncResponse object. ```c++ // Regular, blocking modes cpr::Response delete_response = cpr::Delete(cpr::Url{"http://www.httpbin.org/delete"}); cpr::Response patch_response = cpr::Patch(cpr::Url{"http://www.httpbin.org/patch"}); cpr::Response head_response = cpr::Head(cpr::Url{"http://www.httpbin.org/get"}); cpr::Response options_response = cpr::OPTIONS(cpr::Url{"http://www.httpbin.org/get"}); // Asynchronous, future mode AsyncResponse async_delete_response = cpr::DeleteAsync(cpr::Url{"http://www.httpbin.org/delete"}); AsyncResponse async_patch_response = cpr::PatchAsync(cpr::Url{"http://www.httpbin.org/get"}); AsyncResponse async_head_response = cpr::HeadAsync(cpr::Url{"http://www.httpbin.org/get"}); AsyncResponse async_options_response = cpr::OptionsAsync(cpr::Url{"http://www.httpbin.org/get"}); ``` -------------------------------- ### GET Request with URL Parameters Source: https://github.com/libcpr/docs/blob/main/introduction.md Add URL-encoded parameters to a GET request using the cpr::Parameters object. The order of options does not affect the outcome. ```c++ cpr::Response r = cpr::Get(cpr::Url{"http://www.httpbin.org/get"}, cpr::Parameters{{"hello", "world"}}); // Url object before Parameters std::cout << r.url << std::endl; // http://www.httpbin.org/get?hello=world std::cout << r.text << std::endl; /* * { * "args": { * "hello": "world" * }, * "headers": { * .. * }, * "url": "http://httpbin.org/get?hello=world" * } */ ``` ```c++ cpr::Response r = cpr::Get(cpr::Parameters{{"hello", "world"}}, cpr::Url{"http://www.httpbin.org/get"}); // Parameters object before Url ``` -------------------------------- ### Provide Client Certificate and Private Key (File Path) Source: https://github.com/libcpr/docs/blob/main/advanced-usage.md Authenticate to HTTPS services requiring client certificates by specifying the paths to the certificate and private key files. Supports PEM format by default. ```c++ cpr::SslOptions sslOpts = cpr::Ssl(ssl::CertFile{"cert.pem"}, ssl::KeyFile{"key.pem"}); cpr::Response r = cpr::Get(cpr::Url{"https://www.httpbin.org/get"}, sslOpts); ``` -------------------------------- ### Configure Redirect Behavior Source: https://github.com/libcpr/docs/blob/main/advanced-usage.md Customize redirect handling, including the maximum number of redirects, whether to follow 3xx redirects, send credentials across host changes, and specific behaviors for POST redirects. ```c++ cpr::Response r = cpr::Post(cpr::Url{"http://www.httpbin.org/get"}, cpr::Payload{{"key", "value"}}, cpr::Redirect{42L, true, false, PostRedirectFlags::POST_301 | PostRedirectFlags::POST_302}); ``` -------------------------------- ### Execute Multiple GET Requests with MultiPerform in C++ Source: https://github.com/libcpr/docs/blob/main/advanced-usage.md Execute a GET request on all sessions added to a cpr::MultiPerform object. This function returns a vector of cpr::Response objects, one for each executed request. ```c++ // Perform GET request on all previously added sessions std::vector responses = multiperform.Get(); ``` -------------------------------- ### Build and run a cpr project with Meson Source: https://github.com/libcpr/docs/blob/main/index.md Compile and execute a cpr project managed by Meson. This sequence sets up the build directory, compiles the project, and then runs the executable. ```bash meson setup builddir --wipe meson compile -C builddir ./builddir/cpr-test ``` -------------------------------- ### Setting SSE Callback using SetOption in C++ Source: https://github.com/libcpr/docs/blob/main/sse.md Demonstrates an alternative method to configure the Server-Sent Events callback using the `SetOption` method on a cpr::Session object. This approach is useful for chaining multiple options. ```c++ #include #include int main() { cpr::Session session; session.SetOption(cpr::Url{"https://example.com/events"}); session.SetOption( cpr::ServerSentEventCallback{ [](cpr::ServerSentEvent&& event, intptr_t /*userdata*/) { std::cout << event.data << std::endl; return true; } } ); session.Get(); return 0; } ``` -------------------------------- ### GET Request Source: https://context7.com/libcpr/docs/llms.txt `cpr::Get` performs a synchronous HTTP GET request. URL-encoded query parameters can be attached via `cpr::Parameters`. The returned `cpr::Response` object provides access to status code, text, headers, and more. ```APIDOC ## GET Request ### Description Performs a synchronous HTTP GET request. URL-encoded query parameters are attached via `cpr::Parameters` and can be passed in any argument order. The returned `cpr::Response` exposes `status_code`, `text`, `header`, `url`, `elapsed`, `cookies`, and `error`. ### Method GET ### Endpoint [URL provided in cpr::Url] ### Parameters #### Query Parameters - **Parameters** (cpr::Parameters) - Optional - Key-value pairs to be URL-encoded and appended to the URL. #### Other Options - **Url** (cpr::Url) - Required - The URL to send the GET request to. - **Authentication** (cpr::Authentication) - Optional - Credentials for HTTP Basic Authentication. ### Request Example ```cpp #include #include int main() { cpr::Response r = cpr::Get( cpr::Url{"https://api.github.com/repos/libcpr/cpr/contributors"}, cpr::Authentication{"user", "pass", cpr::AuthMode::BASIC}, cpr::Parameters{{"anon", "true"}, {"key", "value"}} ); if (r.status_code == 0) { std::cerr << "Connection error: " << r.error.message << std::endl; } else if (r.status_code >= 400) { std::cerr << "HTTP error: " << r.status_code << std::endl; } else { std::cout << "URL: " << r.url << std::endl; std::cout << "Status: " << r.status_code << std::endl; std::cout << "Content-Type: " << r.header["content-type"] << std::endl; std::cout << "Time: " << r.elapsed << "s" << std::endl; std::cout << "Body: " << r.text << std::endl; } } ``` ### Response #### Success Response (200) - **status_code** (int) - The HTTP status code of the response. - **text** (string) - The response body as a string. - **header** (cpr::Header) - A map of response headers. - **url** (cpr::Url) - The final URL after any redirects. - **elapsed** (double) - The time taken for the request in seconds. - **cookies** (cpr::Cookies) - A map of cookies returned in the response. - **error** (cpr::Error) - Information about any connection or request errors. #### Response Example ```json { "url": "https://api.github.com/...?anon=true&key=value", "status_code": 200, "content_type": "application/json; charset=utf-8", "elapsed_time_s": 0.5, "body": "[...JSON array...]" } ``` ``` -------------------------------- ### Download File to Memory with Callback Source: https://github.com/libcpr/docs/blob/main/advanced-usage.md Use GetDownloadFileLength to determine the file size and allocate memory before downloading. The write_data callback function handles writing chunks of data to the allocated buffer. Ensure to free the allocated buffer after use. ```c++ struct File { void* file_buf; // file data will be saved to int64_t read_len; // file bytes }; bool write_data(std::string data, intptr_t userdata) { File* pf = reinterpret_cast(userdata); memcpy(pf->file_buf + pf->read_len, data.data(), data.size()); pf->read_len += data.size(); return true; // Return `true` on success, or `false` to **cancel** the transfer. } void download_to_mem(File &f) { cpr::Session session; session.SetUrl(cpr::Url{"http://www.httpbin.org/1.jpg"}); f.read_len = session.GetDownloadFileLength(); f.file_buf = malloc(f.read_len); cpr::Result r = session.Download(cpr::WriteCallback{write_data, reinterpret_cast(&f)}); } int main() { File f{nullptr, 0}; download_to_mem(f); // do something free(f.file_buf); // free file data buf return 0; } ``` -------------------------------- ### Perform a Synchronous GET Request Source: https://context7.com/libcpr/docs/llms.txt Use `cpr::Get` for synchronous HTTP GET requests. URL-encoded query parameters are attached via `cpr::Parameters`. The `cpr::Response` object provides access to status code, body text, headers, and timing information. ```cpp #include #include int main() { // Simple GET cpr::Response r = cpr::Get( cpr::Url{"https://api.github.com/repos/libcpr/cpr/contributors"}, cpr::Authentication{"user", "pass", cpr::AuthMode::BASIC}, cpr::Parameters{{"anon", "true"}, {"key", "value"}} ); if (r.status_code == 0) { std::cerr << "Connection error: " << r.error.message << std::endl; } else if (r.status_code >= 400) { std::cerr << "HTTP error: " << r.status_code << std::endl; } else { std::cout << "URL: " << r.url << std::endl; // https://api.github.com/...?anon=true&key=value std::cout << "Status: " << r.status_code << std::endl; // 200 std::cout << "Content-Type: " << r.header["content-type"] << std::endl; // application/json; charset=utf-8 std::cout << "Time: " << r.elapsed << "s" << std::endl; std::cout << "Body: " << r.text << std::endl; // JSON array } } ``` -------------------------------- ### Other Request Methods (Callback) Source: https://github.com/libcpr/docs/blob/main/advanced-usage.md Shows how to perform DELETE, PATCH, HEAD, and OPTIONS requests using callback functions that process the response asynchronously. ```c++ // Asynchronous, callback mode auto cb_delete_response = cpr::DeleteCallback([](cpr::Response r) { return r.text; }, cpr::Url{"http://www.httpbin.org/delete"}); auto cb_patch_response = cpr::PatchCallback([](cpr::Response r) { return r.text; }, cpr::Url{"http://www.httpbin.org/patch"}); auto cb_head_response = cpr::HeadCallback([](cpr::Response r) { return r.status_code; }, cpr::Url{"http://www.httpbin.org/get"}); auto cb_options_response = cpr::OptionsCallback([](cpr::Response r) { return r.status_code; }, cpr::Url{"http://www.httpbin.org/get"}); ``` -------------------------------- ### Wait for Asynchronous Request Completion Source: https://github.com/libcpr/docs/blob/main/advanced-usage.md Explicitly waits for an asynchronous request to complete using `wait()` before retrieving the response with `get()`. ```c++ cpr::AsyncResponse fr = cpr::GetAsync(cpr::Url{"http://www.httpbin.org/get"}); fr.wait(); // This waits until the request is complete cpr::Response r = fr.get(); // Since the request is complete, this returns immediately std::cout << r.text << std::endl; ``` -------------------------------- ### Default HTTPS Request Source: https://github.com/libcpr/docs/blob/main/advanced-usage.md A standard GET request to an HTTPS URL. CPR automatically handles SSL/TLS verification by default, similar to a web browser. ```c++ cpr::Response r = cpr::Get(cpr::Url{"https://www.httpbin.org/get"}); ``` -------------------------------- ### Execute Multiple Requests Concurrently with Cancellation Source: https://github.com/libcpr/docs/blob/main/advanced-usage.md Bundles multiple requests using `MultiPostAsync` for parallel execution. Demonstrates how to attempt cancellation if a timeout occurs. ```c++ // The second template parameter denotes a cancellable transaction using AsyncResC = cpr::AsyncWrapper; cpr::Url postUrl{"http://www.httpbin.org/post"}; std::vectorresponses{MultiPostAsync( std::tuple{post_url, cpr::Payload{{"name", "Alice"}}}, std::tuple{post_url, cpr::Payload{{"role", "admin"}}} // ... )}; // If the first transaction isn't completed within 10 ms, we'd like to cancel all of them bool all_cancelled{false}; if(responses.at(0).wait_for(std::chrono::milliseconds(10)) == std::future_status::timeout) { all_cancelled = true; for(AsyncResC& res: responses) { all_cancelled &= (res.Cancel() == CancellationResult::success); } } // If not cancelled, process results ``` -------------------------------- ### Build and run a Docker/Podman container for cpr Source: https://github.com/libcpr/docs/blob/main/index.md Build a Docker or Podman container image for cpr and then run it. This command tags the image as 'cpr-image' and maps port 4000, mounts the current directory, and sets the working directory. ```bash podman build . --tag cpr-image podman run --rm -it -p 4000:4000 -v ${PWD}:/app -w /app cpr-image ``` -------------------------------- ### Send Custom Cookies in a Request Source: https://github.com/libcpr/docs/blob/main/advanced-usage.md Sends a GET request with custom cookies specified directly. Useful for testing or when you need to provide specific cookies. ```c++ cpr::Response r = cpr::Get(cpr::Url{"http://www.httpbin.org/cookies"}, cpr::Cookies{{"ice cream", "is delicious"}}); ``` -------------------------------- ### Send Non-URL-Encoded Custom Cookies Source: https://github.com/libcpr/docs/blob/main/advanced-usage.md Sends a GET request with custom cookies, disabling URL encoding. Use this when the server expects unencoded cookie values. ```c++ cpr::Response r = cpr::Get(cpr::Url{"http://www.httpbin.org/cookies"}, cpr::Cookies{{"ice cream", "is delicious"}}, false); std::cout << r.text << std::endl; /* * { * "cookies": { * "ice cream": "is delicious" * } * } */ ``` -------------------------------- ### Integrate C++ Requests with CMake using find_package Source: https://github.com/libcpr/docs/blob/main/index.md Integrates C++ Requests into a CMake project using `find_package` after manual installation. Requires `CPR_USE_SYSTEM_CURL` to be set during the build. ```cmake find_package(cpr REQUIRED) add_executable(your_target_name your_target_name.cpp) target_link_libraries(your_target_name PRIVATE cpr::cpr) ``` -------------------------------- ### Specify Supported HTTP Compression Schemes Source: https://github.com/libcpr/docs/blob/main/advanced-usage.md Configures the Accept-Encoding header to specify supported HTTP compression schemes (deflate, gzip, zlib) for a direct request. ```c++ cpr::Response r = cpr::Get(cpr::Url{"http://www.httpbin.org/get"}, cpr::AcceptEncoding{{cpr::AcceptEncodingMethods::deflate, cpr::AcceptEncodingMethods::gzip, cpr::AcceptEncodingMethods::zlib}}); // or you could specify specific schemes with the customized string cpr::Response r = cpr::Get(cpr::Url{"http://www.httpbin.org/get"}, cpr::AcceptEncoding{{"deflate", "gzip", "zlib"}}); ``` -------------------------------- ### Provide Client Certificate and Private Key (Blob) Source: https://github.com/libcpr/docs/blob/main/advanced-usage.md Authenticate to HTTPS services requiring client certificates by providing the certificate file path and the private key directly as a string blob. Requires libcurl 7.71.0 or newer. ```c++ cpr::SslOptions sslOpts = cpr::Ssl(ssl::CertFile{"cert.pem"}, ssl::KeyBlob{"-----BEGIN RSA PRIVATE KEY-----[...]"}); cpr::Response r = cpr::Get(cpr::Url{"https://www.httpbin.org/get"}, sslOpts); ``` -------------------------------- ### Perform HTTP Multi-Range Request Source: https://github.com/libcpr/docs/blob/main/advanced-usage.md Employ `cpr::MultiRange` to specify multiple byte ranges within a single request. This example requests bytes 1-3 and 5-6. ```c++ cpr::Response r = cpr::Get(cpr::Url{"http://www.httpbin.org/headers"}, cpr::MultiRange{cpr::Range{1, 3}, cpr::Range{5, 6}}); std::cout << r.text << std::endl; /* * { * "headers": { * "Range": "bytes=1-3, 5-6", * ... * } * } */ ``` -------------------------------- ### Perform Simple HTTP Range Request Source: https://github.com/libcpr/docs/blob/main/advanced-usage.md Utilize `cpr::Range` to request a specific byte range from a resource. The example shows requesting bytes 1 through 5. ```c++ cpr::Response r = cpr::Get(cpr::Url{"http://www.httpbin.org/headers"}, cpr::Range{1, 5}); std::cout << r.text << std::endl; /* * { * "headers": { * "Range": "bytes=1-5", * ... * } * } */ ``` -------------------------------- ### Set Session Options using SetOption Source: https://github.com/libcpr/docs/blob/main/advanced-usage.md Configure a Session object using the generic SetOption method, which accepts various configuration objects like Url and Parameters. This offers an alternative to specific Set methods. ```c++ cpr::Url url = cpr::Url{"http://www.httpbin.org/get"}; cpr::Parameters parameters = cpr::Parameters{{"hello", "world"}}; cpr::Session session; session.SetOption(url); session.SetOption(parameters); cpr::Response r = session.Get(); ``` -------------------------------- ### Asynchronous Request with Session Management Source: https://github.com/libcpr/docs/blob/main/advanced-usage.md Performs an asynchronous GET request using a `cpr::Session` object managed by `std::shared_ptr`. The session must be managed by `std::shared_ptr` for lifetime safety. ```c++ std::shared_ptr session = std::make_shared(); cpr::Url url = cpr::Url{"http://www.httpbin.org/get"}; session->SetUrl(url); cpr::AsyncResponse fr = session->GetAsync(); cpr::Response r = fr.get(); std::cout << r.text << std::endl; ``` -------------------------------- ### Stream Live Data Updates using SSE Source: https://github.com/libcpr/docs/blob/main/sse.md Set up an SSE callback to handle live data streams, like stock price updates. The callback can parse incoming data (e.g., JSON) and update the application's state. Return true to maintain the connection. ```c++ cpr::Session session; session.SetUrl(cpr::Url{"https://api.example.com/stock-prices"}); session.SetServerSentEventCallback( cpr::ServerSentEventCallback{ [](cpr::ServerSentEvent&& event, intptr_t /*userdata*/) { if (event.event == "price-update") { // Parse JSON data and update UI std::cout << "Price update: " << event.data << std::endl; } return true; } } ); session.Get(); ``` -------------------------------- ### Pre-allocating Response Buffer with cpr::ReserveSize Source: https://context7.com/libcpr/docs/llms.txt Illustrates using cpr::ReserveSize to pre-allocate the response string buffer, which can improve performance when downloading large payloads by avoiding repeated memory reallocations. ```cpp #include #include int main() { // Reserve 4 MB for a large file response cpr::Response r = cpr::Get( cpr::Url{"http://example.com/large-file.json"}, cpr::ReserveSize{1024 * 1024 * 4} ); std::cout << "Downloaded " << r.downloaded_bytes << " bytes" << std::endl; std::cout << r.text.size() << " chars in body" << std::endl; } ``` -------------------------------- ### Conditional Server-Sent Event Processing in C++ Source: https://github.com/libcpr/docs/blob/main/sse.md Illustrates how to stop receiving Server-Sent Events by returning false from the callback. This example stops processing after 10 events are received, using a counter passed as user data. ```c++ #include #include int main() { int event_count = 0; cpr::Session session; session.SetUrl(cpr::Url{"https://example.com/events"}); session.SetServerSentEventCallback( cpr::ServerSentEventCallback{ [](cpr::ServerSentEvent&& event, intptr_t userdata) { int* count = reinterpret_cast(userdata); (*count)++; std::cout << "Event #" << *count << ": " << event.data << std::endl; // Stop after receiving 10 events return *count < 10; }, reinterpret_cast(&event_count) } ); session.Get(); std::cout << "Processed " << event_count << " events" << std::endl; return 0; } ``` -------------------------------- ### HTTP Methods (PUT, PATCH, DELETE, HEAD, OPTIONS) Source: https://context7.com/libcpr/docs/llms.txt Shows how to perform various HTTP requests including PUT, PATCH, DELETE, HEAD, and OPTIONS using CPR. It also covers asynchronous and callback-based variants. ```APIDOC ## PUT, PATCH, DELETE, HEAD, OPTIONS All HTTP methods follow the same composable interface. Async and callback variants exist for every method. ```cpp #include #include #include int main() { // PUT cpr::Response put_r = cpr::Put( cpr::Url{"http://www.httpbin.org/put"}, cpr::Payload{{"key", "value"}} ); assert(put_r.status_code == 200); // PATCH cpr::Response patch_r = cpr::Patch( cpr::Url{"http://www.httpbin.org/patch"}, cpr::Payload{{"field", "updated"}} ); // DELETE cpr::Response del_r = cpr::Delete(cpr::Url{"http://www.httpbin.org/delete"}); // HEAD (only headers, no body) cpr::Response head_r = cpr::Head(cpr::Url{"http://www.httpbin.org/get"}); std::cout << "Content-Type: " << head_r.header["content-type"] << std::endl; // OPTIONS cpr::Response opt_r = cpr::OPTIONS(cpr::Url{"http://www.httpbin.org/get"}); // Async variants — return AsyncWrapper (like std::future) cpr::AsyncResponse async_del = cpr::DeleteAsync(cpr::Url{"http://www.httpbin.org/delete"}); cpr::AsyncResponse async_head = cpr::HeadAsync(cpr::Url{"http://www.httpbin.org/get"}); std::cout << async_del.get().status_code << std::endl; // 200 std::cout << async_head.get().status_code << std::endl; // 200 // Callback variants — callback receives Response, returns any type auto cb = cpr::DeleteCallback( [](cpr::Response r) { return r.status_code; }, cpr::Url{"http://www.httpbin.org/delete"} ); std::cout << cb.get() << std::endl; // 200 } ``` ``` -------------------------------- ### Implement a Multi-Perform Interceptor in C++ Source: https://github.com/libcpr/docs/blob/main/advanced-usage.md Implement a custom interceptor by inheriting from cpr::InterceptorMulti and overriding the intercept function. Ensure to call proceed() to continue the request. This example logs request URLs and response status codes. ```c++ #include #include #include #include class LoggingInterceptorMulti : public InterceptorMulti { public: std::vector intercept(MultiPerform& multi) { // Log the request URL std::cout << "Request url: " << multi.GetSessions().front().first->GetFullRequestUrl(); << '\n'; // Proceed the request and save the response std::vector response = proceed(multi); // Log response status code std::cout << "Response status code: " << response.front().status_code << '\n'; // Return the stored response return response; } }; int main() { Url url{"https://www.httpbin.org/get"}; std::shared_ptr session = std::make_shared(); session->SetUrl(url); MultiPerform multi; multi.AddSession(session); multi.AddInterceptor(std::make_shared()); std::vector response = multi.Get(); } /* * Output produced by the LoggingInterceptorMulti: * Request url: https://www.httpbin.org/get * Response status code: 200 */ ```