别再只用Curl了!用libhv的HttpClient类,5分钟搞定C++里的GET/POST请求

张开发
2026/4/17 23:34:10 15 分钟阅读

分享文章

别再只用Curl了!用libhv的HttpClient类,5分钟搞定C++里的GET/POST请求
别再只用Curl了用libhv的HttpClient类5分钟搞定C里的GET/POST请求如果你还在用Curl命令行工具或者复杂的libcurl API来处理C项目中的HTTP请求那么是时候认识一下libhv了。这个轻量级、高性能的网络库用起来简直像在写Python一样简单。今天我们就来聊聊如何用libhv的HttpClient类在C项目中优雅地处理各种HTTP请求。1. 为什么选择libhv而不是CurlCurl确实是个强大的工具但在C项目里直接调用curl命令行或者使用libcurl的C API总让人觉得不够现代。libhv的HttpClient类则提供了更符合C开发者习惯的接口设计代码更简洁相比libcurl需要设置大量回调函数libhv的API设计更加直观类型更安全充分利用C的特性避免C风格API中的各种指针和内存管理问题功能更全面内置JSON、表单等常见数据格式的处理开箱即用性能更优基于事件驱动模型支持高并发请求// 对比示例libhv vs libcurl // libhv的GET请求 auto resp requests::get(http://example.com); // libcurl的GET请求 CURL* curl curl_easy_init(); curl_easy_setopt(curl, CURLOPT_URL, http://example.com); curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_callback); curl_easy_perform(curl); curl_easy_cleanup(curl);2. 5分钟快速上手libhv HttpClient2.1 安装与配置首先你需要在项目中引入libhv。最方便的方式是通过vcpkgvcpkg install libhv或者直接从GitHub克隆源码编译git clone https://github.com/ithewei/libhv.git cd libhv mkdir build cd build cmake .. make make install2.2 基本GET/POST请求libhv的HttpClient使用起来异常简单下面是一个完整的示例#include requests.h // libhv提供的简化接口 int main() { // 同步GET请求 auto resp requests::get(http://httpbin.org/get); if (resp) { printf(Status: %d %s\n, resp-status_code, resp-status_message()); printf(Body: %s\n, resp-body.c_str()); } // 同步POST请求JSON数据 auto json_resp requests::post(http://httpbin.org/post, R({key:value})); // 同步POST请求表单数据 auto form_resp requests::post(http://httpbin.org/post, namelibhvtypeawesome); return 0; }2.3 处理各种响应数据libhv内置了对常见数据格式的支持数据类型处理方法示例JSONresp-GetJson()auto json resp-GetJson();表单数据resp-GetFormData()auto value resp-GetFormData(key);文本resp-bodystd::string text resp-body;二进制resp-bodystd::vectorchar data(resp-body.begin(), resp-body.end());3. 高级用法异步请求与自定义配置3.1 异步请求处理对于需要高并发的场景异步请求是更好的选择#include requests.h #include hthread.h void async_callback(const HttpResponsePtr resp) { if (resp) { printf(Async response: %d %s\n, resp-status_code, resp-body.c_str()); } } int main() { // 异步GET请求 requests::getAsync(http://httpbin.org/get, async_callback); // 异步POST请求自定义请求 HttpRequestPtr req(new HttpRequest); req-method HTTP_POST; req-url http://httpbin.org/post; req-headers[Content-Type] application/json; req-body R({async:true}); http_client_send_async(req, async_callback); // 主线程继续执行其他任务... hv_delay(3000); // 等待异步请求完成 return 0; }3.2 请求配置详解HttpRequest类提供了丰富的配置选项HttpRequestPtr req(new HttpRequest); req-method HTTP_GET; req-url http://example.com/api; // 设置头部 req-headers[Accept] application/json; req-headers[Authorization] Bearer token123; // 设置超时秒 req-timeout 10; req-connect_timeout 5; // 设置代理 req-SetProxy(127.0.0.1, 8888); // 允许重定向 req-AllowRedirect(true); // 设置重试策略 req-SetRetry(3, 1000); // 重试3次每次间隔1秒4. 实战构建一个完整的HTTP客户端让我们把这些知识点整合起来构建一个功能完整的HTTP客户端#include requests.h #include iostream class MyHttpClient { public: // 获取JSON数据 hv::Json fetchJson(const std::string url) { auto resp requests::get(url); if (!resp || resp-status_code ! HTTP_STATUS_OK) { throw std::runtime_error(Request failed); } return resp-GetJson(); } // 上传文件 bool uploadFile(const std::string url, const std::string filepath) { HttpRequestPtr req(new HttpRequest); req-method HTTP_POST; req-url url; req-SetFormFile(file, filepath.c_str()); auto resp requests::request(req); return resp resp-status_code HTTP_STATUS_OK; } // 带认证的API请求 hv::Json apiRequest(const std::string url, const std::string token) { HttpRequestPtr req(new HttpRequest); req-method HTTP_GET; req-url url; req-headers[Authorization] Bearer token; auto resp requests::request(req); if (!resp || resp-status_code ! HTTP_STATUS_OK) { throw std::runtime_error(API request failed); } return resp-GetJson(); } }; int main() { MyHttpClient client; try { // 示例获取公开API数据 auto data client.fetchJson(http://httpbin.org/json); std::cout Fetched data: data.dump(2) std::endl; // 示例带认证的请求 auto userData client.apiRequest(http://api.example.com/user, your_token_here); std::cout User data: userData.dump(2) std::endl; } catch (const std::exception e) { std::cerr Error: e.what() std::endl; } return 0; }提示在实际项目中你可能需要添加更完善的错误处理和日志记录。libhv的日志系统可以通过hv::Logger::setLogLevel(hv::Logger::LOG_LEVEL_DEBUG)来启用调试日志。libhv的HttpClient类让C中的HTTP请求变得前所未有的简单。从简单的GET/POST到复杂的文件上传、认证请求都能用几行代码搞定。下次当你的C项目需要处理HTTP通信时不妨试试这个轻量高效的解决方案。

更多文章