在postman中 PUT----》body----》raw----》json
结构体定义:
#define MAX_ARRAY_SIZE 5*1024*1024
struct SMART_DATA_CACHE
{
char* buf;
long dwTotalLen;
SMART_DATA_CACHE()
{
dwTotalLen = 0;
buf = nullptr;
while (!buf) {
try {
buf = new char[MAX_ARRAY_SIZE];
}
catch (...) {}
}
memset(buf, 0x00, MAX_ARRAY_SIZE);
}
~SMART_DATA_CACHE()
{
if (buf) {
delete[] buf;
buf = nullptr;
dwTotalLen = 0;
}
}
};
接收服务器返回信息的函数:
size_t ManageCurl::http_recv_cb(void* ptr, size_t size, size_t nmemb, void* stream)
{
SMART_DATA_CACHE* pDataBuf = (SMART_DATA_CACHE*)stream;
if (pDataBuf) {
if (pDataBuf->buf) {
if (pDataBuf->dwTotalLen + size * nmemb < MAX_ARRAY_SIZE) {
memcpy(pDataBuf->buf + pDataBuf->dwTotalLen, ptr, size * nmemb);
pDataBuf->dwTotalLen += size * nmemb;
}
}
}
return size * nmemb;
}
通过libcurl代码方式:
bool ManageCurl::http_UploadClassID(const char* pUrl, const char* pInfo/*json*/, long nTimeout, SMART_DATA_CACHE& stRecv)
{
bool bResult = false;
//
memset(stRecv.buf, 0, MAX_ARRAY_SIZE);
stRecv.dwTotalLen = 0;
//
CURL* curl = curl_easy_init();
if (curl) {
struct curl_slist* http_header = NULL;
//http_header = curl_slist_append(http_header, "Expect:");
//http_header = curl_slist_append(http_header, "User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US) AppleWebKit/534.3 (KHTML, like Gecko) Chrome/6.0.472.63 Safari/534.3");
http_header = curl_slist_append(http_header, "Charset: UTF-8");
http_header = curl_slist_append(http_header, "Connection: keep-alive");//保持长连接
http_header = curl_slist_append(http_header, "Content-Type: application/json");//保持长连接
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, http_header);//修改协议头
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, http_recv_cb);//设置接收回调
curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void*)&stRecv);//设置设置参数
curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, 10);//设置连接时的超时时间为5秒
curl_easy_setopt(curl, CURLOPT_TIMEOUT, nTimeout);//超时秒为单位
curl_easy_setopt(curl, CURLOPT_URL, pUrl);//指定URL
curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0);
curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0);
curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "PUT"); /* !!! */
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, pInfo); /* data goes here */
CURLcode res = curl_easy_perform(curl);//执行
long nRet = 0;
CURLcode codeRet = curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &nRet);
if (codeRet == CURLE_OK && nRet == 200) {
bResult = true;
}
curl_easy_cleanup(curl);
curl_slist_free_all(http_header);
}
return bResult;
}