Handling Binary Data in HTTP

How do I send and receive binary data like images over HTTP with C++?

The lesson showed examples of sending and receiving JSON data over HTTP. But in many cases we need to work with binary data as well, such as images, audio files, zip archives, etc.

To send binary data in an HTTP request body, we can use the std::vector<uint8_t> type to represent the raw bytes of the data:

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

int main() {
  std::vector<uint8_t> bytes{0xDE, 0xAD, 0xBE, 0xEF};

  cpr::Url URL{"http://www.example.com/upload"};

  cpr::Header headers{
    {"Content-Type", "application/octet-stream"}
  };

  cpr::Body body{std::string(
    bytes.begin(), bytes.end())};

  cpr::Response r = cpr::Post(URL, headers, body);
}

Here the raw bytes are placed in a std::vector<uint8_t>. The Content-Type header is set to application/octet-stream to indicate the body contains arbitrary binary data. The cpr::Body constructor accepts begin/end iterators so we can initialize it with the contents of the vector.

To receive binary data, we can access the std::vector<uint8_t> directly from the cpr::Response object:

cpr::Url URL{"http://www.example.com/image.png"};

cpr::Response r = cpr::Get(URL);

std::vector<uint8_t> imageBytes = r.bytes;

We can then save these bytes to a file, decode them in memory, or process them further as needed based on the type of binary data it is (determined by the Content-Type header).

Using HTTP in Modern C++

A detailed and practical tutorial for working with HTTP in modern C++ using the cpr library.

Questions & Answers

Answers are generated by AI models and may not have been reviewed. Be mindful when running any code on your device.

Testing HTTP Code Locally
How can I test my HTTP code locally without making real network requests?
Handling Paginated HTTP API Responses
Many HTTP APIs return paginated responses when there is a lot of data. How do I handle this in C++?
Setting Timeouts on HTTP Requests
How can I set a timeout on my HTTP requests to avoid waiting too long for a response?
Security Considerations for HTTP Requests
What security issues do I need to be aware of when making HTTP requests in C++?
Mocking HTTP Calls in Unit Tests
How can I unit test code that makes HTTP requests without actually making network calls?
Or Ask your Own Question
Get an immediate answer to your specific question using our AI assistant