When making HTTP requests to external services, there's always a chance the server will be slow to respond or unavailable. We don't want our application to hang indefinitely waiting for a response.
The cpr library allows setting timeouts on requests to mitigate this:
#include <cpr/cpr.h>
#include <iostream>
#include <chrono>
int main() {
// Request times out after 1 second
cpr::Timeout timeout{std::chrono::seconds{1}};
// A url that will take 2 seconds to respond
cpr::Url URL{"http://www.httpbin.org/delay/2"};
cpr::Response r = cpr::Get(URL, timeout);
if (r.error) {
std::cout << r.error.message;
}
}
Operation timed out after 1013 milliseconds with 0 bytes received
Here we create a cpr::Timeout
object representing 1 seconds. This is passed to cpr::Get
. We can detect timeouts and handle them appropriately, perhaps by retrying the request or showing an error message to the user.
The cpr::Timeout
constructor takes any std::chrono::duration
, so we can easily specify the timeout in seconds, milliseconds, etc:
cpr::Timeout t1{std::chrono::seconds{5}};
cpr::Timeout t2{std::chrono::milliseconds{500}};
We can also set connection and low-speed limits:
#include <cpr/cpr.h>
#include <iostream>
#include <chrono>
int main() {
// A url that will take 4 seconds to respond
cpr::Url URL{"http://www.httpbin.org/delay/4"};
// Abort if not connected within 3 seconds
cpr::ConnectTimeout ctimeout{
std::chrono::seconds{3}};
// Abort if transfer speed < 1 byte/sec
// for 3 seconds
cpr::LowSpeed ls{1, 3};
cpr::Response r = cpr::Get(URL, ctimeout, ls);
if (r.error) {
std::cout << r.error.message;
}
}
Operation too slow. Less than 1 bytes/sec transferred the last 3 seconds
cpr::ConnectTimeout
limits how long to wait to establish the initial TCPÂ connection.
cpr::LowSpeed
aborts if the transfer speed is below a threshold for a given duration. This prevents "stalling" even after the connection is established.
By tweaking these policies we can fine-tune the behavior of our HTTP clients and avoid slowdowns due to unresponsive servers.
Answers to questions are automatically generated and may not have been reviewed.
A detailed and practical tutorial for working with HTTP in modern C++ using the cpr
library.