在C++中使用libcurl发送和接收POST请求可以通过以下步骤实现:
下面是一个示例代码:
#include <curl/curl.h>
#include <iostream>
size_t WriteCallback(void* contents, size_t size, size_t nmemb, std::string* response) {
size_t totalSize = size * nmemb;
response->append((char*)contents, totalSize);
return totalSize;
}
int main() {
CURL* curl = curl_easy_init();
if (curl) {
std::string url = "http://example.com/api";
std::string postData = "key1=value1&key2=value2";
curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
curl_easy_setopt(curl, CURLOPT_POST, 1);
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, postData.c_str());
std::string response;
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &response);
CURLcode res = curl_easy_perform(curl);
if (res == CURLE_OK) {
long responseCode;
curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &responseCode);
std::cout << "Response Code: " << responseCode << std::endl;
std::cout << "Response Body: " << response << std::endl;
} else {
std::cerr << "Request failed: " << curl_easy_strerror(res) << std::endl;
}
curl_easy_cleanup(curl);
}
return 0;
}
在上述示例代码中,我们使用了一个WriteCallback函数作为接收响应数据的回调函数。该函数将接收到的数据追加到response字符串中。
请注意,这只是一个简单的示例,实际应用中可能需要处理更多的错误和异常情况,并进行适当的错误处理。
推荐的腾讯云相关产品:腾讯云CDN(内容分发网络),详情请参考:https://cloud.tencent.com/product/cdn
领取专属 10元无门槛券
手把手带您无忧上云