cpp-httplib v0.42.0
DRAFT

C12. Set Timeouts

The client has three kinds of timeouts, each set independently.

KindAPIDefaultMeaning
Connectionset_connection_timeout300sTime to wait for the TCP connection to establish
Readset_read_timeout300sTime to wait for a single recv when receiving the response
Writeset_write_timeout5sTime to wait for a single send when sending the request

Basic usage

httplib::Client cli("http://localhost:8080");

cli.set_connection_timeout(5, 0);  // 5 seconds
cli.set_read_timeout(10, 0);       // 10 seconds
cli.set_write_timeout(10, 0);      // 10 seconds

auto res = cli.Get("/api/data");
httplib::Client cli("http://localhost:8080");

cli.set_connection_timeout(5, 0);  // 5 seconds
cli.set_read_timeout(10, 0);       // 10 seconds
cli.set_write_timeout(10, 0);      // 10 seconds

auto res = cli.Get("/api/data");

Pass seconds and microseconds as two arguments. If you don't need the sub-second part, you can omit the second argument.

Use std::chrono

There's also an overload that takes a std::chrono duration directly. It's easier to read — recommended.

using namespace std::chrono_literals;

cli.set_connection_timeout(5s);
cli.set_read_timeout(10s);
cli.set_write_timeout(500ms);
using namespace std::chrono_literals;

cli.set_connection_timeout(5s);
cli.set_read_timeout(10s);
cli.set_write_timeout(500ms);

Watch out for the long 300s default

Connection and read timeouts default to 300 seconds (5 minutes). If the server hangs, you'll be waiting five minutes by default. Shorter values are usually a better idea.

cli.set_connection_timeout(3s);
cli.set_read_timeout(10s);
cli.set_connection_timeout(3s);
cli.set_read_timeout(10s);

Warning: The read timeout covers a single receive call — not the whole request. If data keeps trickling in during a large download, the request can take half an hour without ever hitting the timeout. To cap the total request time, use C13. Set an overall timeout.

ESC