我使用的是curl-7.84.0.zip,编译过程不再多说
http接口代码是跨平台的
#include "curl/curl.h"
size_t receive_data(void* buffer, size_t size, size_t nmemb, void* lpVoid)
{
std::string* str = dynamic_cast<std::string*>((std::string*)lpVoid);
if (NULL == str || NULL == buffer)
{
return -1;
}
char* pData = (char*)buffer;
str->append(pData, size * nmemb);
return nmemb;
}
bool HttpUpload(const std::string& strUrl, const std::string& localFile, const std::string& remoteFile, const long nTimeout)
{
curl_global_init(CURL_GLOBAL_DEFAULT);
CURL* curl = curl_easy_init();
CURLcode res;
std::string strData;
struct curl_httppost* post = NULL;
struct curl_httppost* last = NULL;
if (curl)
{
curl_easy_setopt(curl, CURLOPT_URL, strUrl.c_str());
curl_easy_setopt(curl, CURLOPT_READFUNCTION, NULL);
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, receive_data);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void*)&strData);
curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1);
curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, 6);
curl_easy_setopt(curl, CURLOPT_TIMEOUT, nTimeout);
curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0L);
curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0L);
curl_formadd(&post, &last, CURLFORM_PTRNAME, "file", CURLFORM_FILE, localFile.c_str(), CURLFORM_FILENAME, remoteFile.c_str(), CURLFORM_END);
curl_easy_setopt(curl, CURLOPT_HTTPPOST, post);
res = curl_easy_perform(curl);
if (res != CURLE_OK)
{
return false;
}
curl_easy_cleanup(curl);
curl_global_cleanup();
}
else
{
return false;
}
return true;
}
bool HttpGet(const std::string& strUrl, std::string& strData, const long nTimeout)
{
curl_global_init(CURL_GLOBAL_DEFAULT);
CURL* curl = curl_easy_init();
CURLcode res;
if (curl)
{
curl_easy_setopt(curl, CURLOPT_URL, strUrl.c_str());
curl_easy_setopt(curl, CURLOPT_READFUNCTION, NULL);
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, receive_data);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void*)&strData);
curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1);
curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, 6);
curl_easy_setopt(curl, CURLOPT_TIMEOUT, nTimeout);
curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0L);
curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0L);
res = curl_easy_perform(curl);
if (res != CURLE_OK)
{
return false;
}
if (strData.compare("error") == 0)
{
return false;
}
curl_easy_cleanup(curl);
curl_global_cleanup();
}
else
{
return false;
}
return true;
}