Using HTTP in Modern C++

Handling Binary Data in HTTP

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

Abstract art representing computer programming

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).

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