C++ Requests: Curl for People

Trying out CPR project.

vcpkg search cpr
cpr  1.6.2     C++ Requests is a simple wrapper around libcurl inspired by the excellent ...

So it’s installable via vcpkg install cpr.

I must say it just worked, this is the code I had to write:

#include <iostream>
#include <cpr/cpr.h>

int main()
{
    cpr::Response r = cpr::Get(cpr::Url{ "https://bbc.co.uk" });
}

So CPR understands HTTP(S) and really easy to use. It just works which is a big win, and the official docs are great.

Standard command like Get, Post, Head, Delete, Options, Put, Patch are supported.

Built-in support for Basic, Digest, HTML, OAuth authentication is there.

Scenario: Resolving Bit.ly URLs

bit.ly is an URL shortener - you give it something long and it can generate a short one so you can share it where space is limited. I’ve tried to use CPR to resolve bit.ly URLs, like https://bit.ly/3koe9Ii which should point to https://www.aloneguid.uk/posts/.

Calling just cpr::Get(cpr::Url{ "https://bit.ly/3koe9Ii" }); worked perfectly - cpr did understand the redirect, went to the target URL and fetched html text for https://www.aloneguid.uk/posts/. This is because of great default behavior - “just work”. But what if we want not to redirect? With cpr it’s easy, as author says in the docs:

In cpr, options are actually options so if you don’t set them they’ll default to sensible values. This is facilitated by the keyword args-like interface:

cpr::Response r = cpr::Get(cpr::Url{"http://www.httpbin.org/get"},
                  cpr::Parameters{{"hello", "world"}}); // Url object before Parameters

There are plenty built-in options, but I found the one I needed - MaxRedirects:

cpr::Response bitly = cpr::Get(cpr::Url{ "https://bit.ly/3koe9Ii" }, cpr::MaxRedirects{ 0 });
std::string resolved = bitly.header["Location"];

and resolved now contains "https://www.aloneguid.uk/posts/".

Job done ☕

Overhead

On Windows, this simple executable compiles to 276 kb in debug mode, and 46 kb in release mode. However, there are external dependencies:

  • libcurl.dll - 421 kb
  • zlib1.dll - 73 kb

One can probably link those statically and reduce the size, but that’s an exercise for another day.


To contact me, send an email anytime or leave a comment below.