Skip to content

Yaznbook/rcj

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

1 Commit
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

RequestC++JSON (RCJ) Library By Yaznbook

A modern C++ library for making HTTP requests and handling JSON data with a clean, easy-to-use API.

Features

  • HTTP Requests: Support for GET, POST, PUT, DELETE, PATCH, HEAD, and OPTIONS methods
  • JSON Handling: Built-in JSON parsing and manipulation using nlohmann/json
  • Easy Linking: Shared library that can be easily linked to any C++ project
  • Modern C++: Uses C++17 features and RAII principles
  • Thread-Safe: Designed for concurrent usage
  • SSL/TLS Support: Built-in HTTPS support with certificate verification

Requirements

  • CMake 3.16 or higher
  • C++17 compatible compiler (GCC 7+, Clang 5+, MSVC 2017+)
  • libcurl development libraries
  • pthread (usually included with the compiler)

Installing Dependencies (Ubuntu/Debian)

sudo apt update
sudo apt install build-essential cmake libcurl4-openssl-dev

Installing Dependencies (CentOS/RHEL/Fedora)

sudo yum install gcc gcc-c++ cmake libcurl-devel
# or for newer versions:
sudo dnf install gcc gcc-c++ cmake libcurl-devel

Building the Library

# Clone or download the library
cd rcj

# Create build directory
mkdir build && cd build

# Configure with CMake
cmake ..

# Build the library
make

# Install (optional, requires root/admin privileges)
sudo make install

Linking to Your Project

Using CMake (Recommended)

Add to your CMakeLists.txt:

# Find the RCJ library
find_package(RCJ REQUIRED)

# Link to your executable
add_executable(your_app main.cpp)
target_link_libraries(your_app RCJ::RCJ)

If RCJ is not installed system-wide, you can also use it as a subdirectory:

# Add RCJ as a subdirectory
add_subdirectory(path/to/rcj)

# Link to your executable
add_executable(your_app main.cpp)
target_link_libraries(your_app RCJ)

Manual Linking

If you're not using CMake, link with:

g++ your_app.cpp -lrcj -lcurl -pthread

Usage Examples

Basic GET Request

#include <RCJ/RCJ.hpp>
#include <iostream>

int main() {
    RCJ::Request request;
    RCJ::Response response = request
        .setUrl("https://jsonplaceholder.typicode.com/posts/1")
        .execute();

    if (response.isSuccess()) {
        std::cout << "Response: " << response.body() << std::endl;

        // Parse JSON
        RCJ::JsonValue json = response.json();
        if (json.isObject()) {
            std::cout << "Title: " << json["title"].asString() << std::endl;
        }
    } else {
        std::cout << "Error: " << response.statusCode() << std::endl;
    }

    return 0;
}

POST Request with JSON

#include <RCJ/RCJ.hpp>
#include <iostream>

int main() {
    // Create JSON data
    RCJ::JsonValue postData;
    postData["title"] = "New Post";
    postData["body"] = "This is the content of the post";
    postData["userId"] = 1;

    RCJ::Request request;
    RCJ::Response response = request
        .setUrl("https://jsonplaceholder.typicode.com/posts")
        .setMethod(RCJ::HttpMethod::POST)
        .setJsonBody(postData)
        .execute();

    if (response.isSuccess()) {
        std::cout << "Created post: " << response.body() << std::endl;
    }

    return 0;
}

Working with JSON Data

#include <RCJ/RCJ.hpp>
#include <iostream>

int main() {
    // Parse JSON string
    std::string jsonStr = R"(
        {
            "name": "John Doe",
            "age": 30,
            "hobbies": ["reading", "coding", "gaming"],
            "address": {
                "street": "123 Main St",
                "city": "Anytown"
            }
        }
    )";

    RCJ::JsonValue person = RCJ::JsonValue::parse(jsonStr);

    // Access data
    std::cout << "Name: " << person["name"].asString() << std::endl;
    std::cout << "Age: " << person["age"].asInt() << std::endl;

    // Access array
    RCJ::JsonValue hobbies = person["hobbies"];
    if (hobbies.isArray()) {
        auto hobbyList = hobbies.asArray();
        for (size_t i = 0; i < hobbyList.size(); ++i) {
            std::cout << "Hobby " << i << ": " << hobbyList[i].asString() << std::endl;
        }
    }

    // Access nested object
    std::cout << "City: " << person["address"]["city"].asString() << std::endl;

    // Create new JSON
    RCJ::JsonValue newPerson;
    newPerson["name"] = "Jane Smith";
    newPerson["age"] = 25;

    std::cout << "JSON: " << newPerson.toString(true) << std::endl;

    return 0;
}

Custom Headers and Timeout

#include <RCJ/RCJ.hpp>
#include <iostream>

int main() {
    RCJ::Request request;
    RCJ::Response response = request
        .setUrl("https://api.example.com/data")
        .setMethod(RCJ::HttpMethod::GET)
        .setHeader("Authorization", "Bearer your-token-here")
        .setHeader("User-Agent", "RCJ-Library/1.0")
        .setTimeout(10000) // 10 seconds
        .execute();

    if (response.isSuccess()) {
        std::cout << "Data received successfully" << std::endl;
    }

    return 0;
}

API Reference

RCJ::Request

  • setUrl(const std::string& url) - Set the request URL
  • setMethod(HttpMethod method) - Set HTTP method (GET, POST, etc.)
  • setHeader(const std::string& key, const std::string& value) - Add HTTP header
  • setBody(const std::string& body) - Set request body
  • setJsonBody(const JsonValue& json) - Set JSON request body
  • setTimeout(int timeoutMs) - Set request timeout in milliseconds
  • execute() - Execute the request and return Response

RCJ::Response

  • statusCode() - Get HTTP status code
  • statusText() - Get status text
  • body() - Get response body as string
  • json() - Parse response body as JSON
  • headers() - Get all response headers
  • header(const std::string& key) - Get specific header value
  • isSuccess() - Check if status code indicates success (200-299)

RCJ::JsonValue

  • isNull(), isBool(), isNumber(), isString(), isArray(), isObject() - Type checking
  • asBool(), asInt(), asDouble(), asString() - Value extraction
  • asArray(), asObject() - Get as array/object
  • operator[](size_t index), operator[](const std::string& key) - Array/object access
  • toString(bool pretty = false) - Convert to JSON string
  • parse(const std::string& jsonString) - Parse JSON string
  • fromFile(const std::string& filePath) - Load JSON from file

RCJ::utils

  • urlEncode(const std::string& str) - URL encode string
  • urlDecode(const std::string& str) - URL decode string
  • base64Encode(const std::string& str) - Base64 encode
  • base64Decode(const std::string& str) - Base64 decode
  • toLower(const std::string& str) - Convert to lowercase
  • toUpper(const std::string& str) - Convert to uppercase
  • trim(const std::string& str) - Trim whitespace

Error Handling

The library uses exceptions for error conditions. Always wrap your code in try-catch blocks:

try {
    RCJ::JsonValue json = RCJ::JsonValue::parse(malformedJson);
} catch (const std::exception& e) {
    std::cout << "JSON parse error: " << e.what() << std::endl;
}

Thread Safety

The library is designed to be thread-safe. You can create multiple Request objects in different threads without issues.

License

MIT Lincense

Contributing

Feel free to submit issues and pull requests to improve the library.

About

RCJ (RequestC++JSON) by Yaznbook Open Source

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors