用c++的curl发送body为json格式的post请求
时间: 2024-06-07 22:12:05 浏览: 14
在C++中发送body为json格式的POST请求可以使用curl库。下面是一个简单的例子:
```c++
#include <iostream>
#include <curl/curl.h>
int main() {
CURL* curl = curl_easy_init();
if (curl) {
// 设置URL
curl_easy_setopt(curl, CURLOPT_URL, "http://example.com/api");
// 设置HTTP请求头
struct curl_slist *headers = NULL;
headers = curl_slist_append(headers, "Content-Type: application/json");
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
// 设置HTTP请求体
const char* data = "{\"key\": \"value\"}";
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, data);
// 发送请求
CURLcode res = curl_easy_perform(curl);
if (res != CURLE_OK) {
std::cerr << "curl_easy_perform() failed: " << curl_easy_strerror(res) << std::endl;
}
// 清理
curl_slist_free_all(headers);
curl_easy_cleanup(curl);
}
return 0;
}
```
在上面的例子中,我们首先初始化了一个curl对象。然后设置了请求的URL、HTTP请求头和HTTP请求体。最后使用`curl_easy_perform()`函数发送请求。如果请求发送成功,`curl_easy_perform()`函数会返回`CURLE_OK`,否则返回一个错误码。最后,我们清理了请求头和curl对象。
需要注意的是,上面的例子只是一个简单的示例,实际使用时可能需要根据具体情况进行调整。也可以使用第三方库,如cpprestsdk、rapidjson等来方便地处理JSON数据。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)