size_t http_data_writer(void* data, size_t size, size_t nmemb, void* content)
{
long totalSize = size*nmemb;
std::string* symbolBuffer = (std::string*)content;
if(symbolBuffer)
{
symbolBuffer->append((char *)data, ((char*)data)+totalSize);
}
return totalSize;
}
bool AccessWeb(char* szUrl)
{
CURL* curl = NULL;
curl=curl_easy_init();
CURLcode code;
// 设置Url
code = curl_easy_setopt(curl, CURLOPT_URL, szUrl);
// 设置post的json数据
char szPost[64] = "msg=hello";
code = curl_easy_setopt(curl, CURLOPT_POSTFIELDS, szPost);
// 设置回调函数
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_func);
//设置写数据
std::string strData;
curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void*)&strData);
// 执行请求
code = curl_easy_perform(curl);
if(code == CURLcode::CURLE_OK)
{
long responseCode = 0;
curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &responseCode);
if (responseCode < 200 || responseCode >= 300 || strData.empty())
{
return false;
}
//下面可以对应答的数据进行处理了
// strData
}
// 清除curl对象
curl_easy_cleanup(curl);
return true;
}c++使用curl库访问服务器并获取应答结果
最新推荐文章于 2025-09-02 06:06:50 发布
本文介绍了一个使用libcurl库实现的简单C++程序,该程序通过POST方式向指定URL发送JSON数据,并接收服务器响应。文章展示了如何设置libcurl选项,如URL、POST数据和回调函数等,并解释了如何解析HTTP响应状态码。
3万+

被折叠的 条评论
为什么被折叠?



