Using HTTP in Modern C++

Setting Timeouts on HTTP Requests

How can I set a timeout on my HTTP requests to avoid waiting too long for a response?

Abstract art representing computer programming

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.

Free, Unlimited Access

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Screenshot from Warhammer: Total War
Screenshot from Tomb Raider
Screenshot from Jedi: Fallen Order
Contact|Privacy Policy|Terms of Use
Copyright © 2024 - All Rights Reserved