本文作者:icy

C++ CPR:现代化、易用的HTTP客户端库

icy 今天 6 抢沙发
C++ CPR:现代化、易用的HTTP客户端库摘要: C++ CPR:现代化、易用的HTTP客户端库 项目概述 C++ CPR(C++ Requests)是一个受Python Requests库启发的现代化C++ HTTP客户端库。它...

C++ CPR:现代化、易用的HTTP客户端库

C++ CPR:现代化、易用的HTTP客户端库

项目概述

C++ CPR(C++ Requests)是一个受Python Requests库启发的现代化C++ HTTP客户端库。它提供了简洁直观的API,让C++开发者能够轻松地进行HTTP通信,无需处理底层复杂的网络细节。

主要特性

1. 简洁直观的API

text
#include <cpr/cpr.h>

// 简单的GET请求
auto response = cpr::Get(cpr::Url{"https://api.example.com/data"});
std::cout << "Status: " << response.status_code << std::endl;
std::cout << "Body: " << response.text << std::endl;

2. 完整的HTTP方法支持

  • GET、POST、PUT、DELETE、PATCH、HEAD、OPTIONS

3. 丰富的功能

  • URL参数
  • 请求头设置
  • 请求体(JSON、表单数据、文件上传)
  • Cookie管理
  • 超时设置
  • 代理支持
  • 认证(Basic、Digest、Bearer Token)
  • 异步请求
  • 重定向控制

安装与配置

使用vcpkg安装

text
vcpkg install cpr

使用CMake集成

text
find_package(cpr REQUIRED)
target_link_libraries(your_target PRIVATE cpr::cpr)

实用示例

1. 基本GET请求

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

int main() {
    // 带参数的GET请求
    auto response = cpr::Get(
        cpr::Url{"https://httpbin.org/get"},
        cpr::Parameters{{"key1", "value1"}, {"key2", "value2"}}
    );
    
    if (response.status_code == 200) {
        std::cout << "Response: " << response.text << std::endl;
    } else {
        std::cout << "Request failed: " << response.error.message << std::endl;
    }
    
    return 0;
}

2. POST请求(JSON数据)

text
#include <iostream>
#include <cpr/cpr.h>
#include <nlohmann/json.hpp>

int main() {
    // 创建JSON数据
    nlohmann::json data = {
        {"name", "John Doe"},
        {"email", "john@example.com"},
        {"age", 30}
    };
    
    // 发送POST请求
    auto response = cpr::Post(
        cpr::Url{"https://httpbin.org/post"},
        cpr::Header{{"Content-Type", "application/json"}},
        cpr::Body{data.dump()}
    );
    
    std::cout << "Status: " << response.status_code << std::endl;
    std::cout << "Response: " << response.text << std::endl;
    
    return 0;
}

3. 文件上传

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

int main() {
    // 上传文件
    auto response = cpr::Post(
        cpr::Url{"https://httpbin.org/post"},
        cpr::Multipart{
            {"file", cpr::File{"path/to/file.txt"}},
            {"description", "This is a test file"}
        }
    );
    
    std::cout << "Upload status: " << response.status_code << std::endl;
    
    return 0;
}

4. 带认证的请求

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

int main() {
    // Basic认证
    auto response = cpr::Get(
        cpr::Url{"https://httpbin.org/basic-auth/user/pass"},
        cpr::Authentication{"user", "pass", cpr::AuthMode::BASIC}
    );
    
    // Bearer Token认证
    auto token_response = cpr::Get(
        cpr::Url{"https://api.example.com/protected"},
        cpr::Bearer{"your_token_here"}
    );
    
    return 0;
}

5. 异步请求

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

int main() {
    // 发起异步请求
    std::future<cpr::Response> future = cpr::GetAsync(
        cpr::Url{"https://httpbin.org/delay/3"}
    );
    
    std::cout << "Request sent, doing other work..." << std::endl;
    
    // 等待响应
    cpr::Response response = future.get();
    
    std::cout << "Async response received: " << response.status_code << std::endl;
    
    return 0;
}

6. 自定义超时和重试

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

int main() {
    // 设置超时和重试策略
    auto response = cpr::Get(
        cpr::Url{"https://httpbin.org/delay/5"},
        cpr::Timeout{3000},  // 3秒超时
        cpr::ConnectTimeout{2000},  // 连接超时2秒
        cpr::LowSpeed{100, 10}  // 10秒内下载速度低于100字节则超时
    );
    
    if (response.status_code == 0) {
        std::cout << "Request timed out or failed" << std::endl;
    }
    
    return 0;
}

错误处理

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

int main() {
    try {
        auto response = cpr::Get(cpr::Url{"https://invalid-url.example"});
        
        if (response.error) {
            std::cerr << "Error: " << response.error.message << std::endl;
            std::cerr << "Error code: " << response.error.code << std::endl;
        }
        
        if (response.status_code >= 400) {
            std::cerr << "HTTP error: " << response.status_code << std::endl;
        }
        
    } catch (const std::exception& e) {
        std::cerr << "Exception: " << e.what() << std::endl;
    }
    
    return 0;
}

与cURL对比的优势

  1. 更简洁的API:相比直接使用libcurl,CPR提供了更高级、更易用的接口
  2. 类型安全:充分利用C++类型系统,减少运行时错误
  3. 现代C++特性:支持RAII、移动语义等现代C++特性
  4. 更好的错误处理:统一的错误处理机制
  5. 线程安全:内置线程安全支持

性能考虑

CPR在libcurl的基础上构建,继承了其优秀的性能特性: - 连接复用 - HTTP/2支持 - 压缩支持 - 高效的DNS解析

适用场景

  1. REST API客户端:与各种Web服务进行通信
  2. Web爬虫:抓取和处理网页数据
  3. 微服务通信:服务间的HTTP通信
  4. 文件下载/上传:处理文件传输
  5. API测试:编写HTTP API测试用例

总结

C++ CPR是一个强大而优雅的HTTP客户端库,它将复杂的HTTP通信简化为几行清晰的C++代码。无论是简单的GET请求还是复杂的多部分文件上传,CPR都能提供直观的解决方案。对于需要在C++项目中进行HTTP通信的开发者来说,CPR是一个值得考虑的优秀选择。

通过其简洁的API、完整的HTTP功能支持和活跃的社区维护,CPR已经成为C++生态系统中HTTP客户端库的重要选择之一。

cpr_20260204073608.zip
类型:压缩文件|已下载:0|下载方式:免费下载
立即下载
文章版权及转载声明

作者:icy本文地址:https://www.zelig.cn/2026/03/407.html发布于 今天
文章转载或复制请以超链接形式并注明出处软角落-SoftNook

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

微信扫一扫打赏

阅读
分享

发表评论

快捷回复:

验证码

评论列表 (暂无评论,6人围观)参与讨论

还没有评论,来说两句吧...