cpprestsdk是C++调用RESTful API最成熟跨平台方案,支持异步、HTTP客户端、JSON解析和URI处理;推荐vcpkg安装,Windows用cpprestsdk:x64-windows,Linux/macOS用x64-linux/x64-osx;示例通过http_client发起GET请求并解析JSON响应。

用 C++ 调用 RESTful API,cpprestsdk(Casablanca) 是目前最成熟、跨平台、原生支持异步的官方推荐方案。它封装了 HTTP 客户端、JSON 解析、URI 处理等能力,无需手动拼接 HTTP 报文或解析 JSON 字符串。
安装 cpprestsdk(Windows / Linux / macOS)
官方推荐通过 vcpkg 管理依赖,避免编译复杂性:
- Windows(Visual Studio):vcpkg install cpprestsdk:x64-windows,然后在 CMake 或 VS 项目中启用 vcpkg 集成
- Linux/macOS:vcpkg install cpprestsdk:x64-linux(或 x64-osx),导出为 system port 或使用 -DCMAKE_TOOLCHAIN_FILE
若需源码编译,注意开启 BUILD_TESTS=OFF 和 BUILD_SAMPLES=OFF 加速构建,并确保已安装 OpenSSL、Boost(部分版本可选)、CMake 3.15+。
发起 GET 请求并解析 JSON 响应
以下是最简可用示例:获取 https://httpbin.org/get 并打印 query 参数回显:
立即学习“C++免费学习笔记(深入)”;
#include <cpprest/http_client.h>
#include <cpprest/json.h>
#include <iostream>
using namespace web;
using namespace web::http;
using namespace web::http::client;
using json = web::json::value;
int main() {
http_client client(U("https://httpbin.org"));
auto resp = client.request(methods::GET, U("/get")).get();
if (resp.status_code() == status_codes::OK) {
auto body = resp.extract_json().get();
std::wcout << L"Origin: " << body[U("origin")].as_string() << std::endl;
}
}
登录后复制
关键点:
标签: linux js json windows ssl mac ai c++ ios macos win stream 网络
还木有评论哦,快来抢沙发吧~