curl写一个发送数据的c++代码
时间: 2023-11-29 17:35:55 浏览: 50
以下是一个使用curl发送POST请求的示例代码:
```C++
#include <iostream>
#include <curl/curl.h>
int main()
{
CURL *curl;
CURLcode res;
curl_global_init(CURL_GLOBAL_ALL);
curl = curl_easy_init();
if (curl) {
std::string data = "Hello, world!"; // 待发送的数据
curl_easy_setopt(curl, CURLOPT_URL, "http://example.com"); // 设置请求的URL
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, data.c_str()); // 设置POST数据
res = curl_easy_perform(curl); // 执行请求
if (res != CURLE_OK) {
std::cerr << "curl_easy_perform() failed: " << curl_easy_strerror(res) << std::endl;
}
curl_easy_cleanup(curl);
}
curl_global_cleanup();
return 0;
}
```
在上面的示例代码中,我们使用了libcurl库来发送HTTP请求,首先调用`curl_global_init()`函数进行全局初始化,然后创建一个CURL对象并设置请求的URL和POST数据,最后调用`curl_easy_perform()`函数执行请求,并检查返回值是否为CURLE_OK。最后我们在程序结束前调用`curl_global_cleanup()`函数释放资源。
相关推荐
![](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)