c++ post RequestBody
时间: 2024-04-25 20:19:04 浏览: 158
在C++中发送POST请求并携带RequestBody,你可以使用第三方库,比如cURL来实现。cURL是一个功能强大的开源库,可以用于发送HTTP请求。
以下是一个使用cURL发送POST请求并携带RequestBody的示例代码:
```cpp
#include <iostream>
#include <curl/curl.h>
int main() {
CURL *curl;
CURLcode res;
// 初始化cURL
curl_global_init(CURL_GLOBAL_DEFAULT);
curl = curl_easy_init();
if(curl) {
// 设置请求的URL
curl_easy_setopt(curl, CURLOPT_URL, "http://example.com/api");
// 设置请求方式为POST
curl_easy_setopt(curl, CURLOPT_POST, 1L);
// 设置RequestBody
std::string requestBody = "key1=value1&key2=value2";
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, requestBody.c_str());
// 发送请求
res = curl_easy_perform(curl);
if(res != CURLE_OK) {
std::cerr << "Failed to send POST request: " << curl_easy_strerror(res) << std::endl;
}
// 清理cURL资源
curl_easy_cleanup(curl);
}
// 清理全局cURL资源
curl_global_cleanup();
return 0;
}
```
上述代码使用了cURL库来发送POST请求,并通过`CURLOPT_POSTFIELDS`选项设置了RequestBody。你可以将`http://example.com/api`替换为你实际要发送请求的URL,将`requestBody`替换为你要发送的具体数据。
阅读全文
相关推荐
















