最近一直在忙于一个项目,项目上使用到了使用HTTP/POST方法往服务器推送JSON格式数据,通过以下地址链接:https://curl.haxx.se/download.html下载源代码之后,按照要求进行编译,编译libCurl库之后,通过源代码目录中给出的demo学习了一番。把当时测试的demo列出来了:
- #include <curl/curl.h>
- #include <string.h>
- #include <exception>
- #include <stdio.h>
- #include <unistd.h>
-
- using namespace std;
- static size_t WriteMemoryCallback(void *ptr, size_t size, size_t nmemb, void *data)
- {
- size_t realsize = size * nmemb;
- char *buffer = (char *)data;
- if(buffer)
- {
- memmove(buffer, (char *)ptr, realsize);
- printf("buffer:%s\n", (char *)ptr);
- }
- return realsize;
- }
-
- void SendHttpPost(CURL *pCurl)
- {
- char szJsonData[1024];
- memset(szJsonData, 0, sizeof(szJsonData));
- snprintf(szJsonData, 1024,"{"
- "\"request\":{"
- "\"action\":\"Status\","
- "\"content\":{" "\"DEVICE\":\"1234567890\","
- "\"STATE\":\"Online\","
- "\"DYJD\":\"null\","
- "\"DYWD\":\"null\""
- "}"
- "}"
- "}");
- try
- {
- CURL *pCurl = NULL;
- CURLcode res;
- char recv[128] = {0};
- //this will init the winsock stuff
- curl_global_init(CURL_GLOBAL_ALL);
-
- // get a curl handle
- pCurl = curl_easy_init();
- if (NULL != pCurl)
- {
- // 设置超时时间为1秒
- curl_easy_setopt(pCurl, CURLOPT_TIMEOUT, 1);
- curl_easy_setopt(pCurl, CURLOPT_URL, "http://192.168.1.7:8888/videotest/unAuth/State");
-
- // 设置http发送的内容类型为JSON
- curl_slist *plist = curl_slist_append(NULL,"Content-Type:application/json;charset=UTF-8");
- curl_easy_setopt(pCurl, CURLOPT_HTTPHEADER, plist);
-
- // 设置要POST的JSON数据
- curl_easy_setopt(pCurl, CURLOPT_POSTFIELDS, szJsonData);
- //curl_easy_setopt(pCurl, CURLOPT_WRITEFUNCTION, WriteMemoryCallback);
- //curl_easy_setopt(pCurl, CURLOPT_WRITEDATA, (void*)recv);
-
- // Perform the request, res will get the return code
- res = curl_easy_perform(pCurl);
- // Check for errors
- if (res != CURLE_OK)
- {
- printf("curl_easy_perform() failed:%s\n", curl_easy_strerror(res));
- }
- // always cleanup
- printf("curl_easy_perform success! receive json data\n");
- curl_easy_cleanup(pCurl);
- }
- curl_global_cleanup();
- }
- catch (std::exception &ex)
- {
- printf("curl exception %s.\n", ex.what());
- }
-
- }
-
- int main(int argc, char *argv[])
- {
- int nCount = 3000;
- while(nCount--)
- {
- SendHttpPost(pCurl);
- printf("nCount--: <%d>\n", nCount);
- usleep(200000);
- }
-
- while(1)
- {
- printf("xunhuan!!!!\n");
- usleep(1000000);
- }
-
- return 0;
- }
-
上述代码测试后发现使用top命令查看该进程的资源使用情况,发现RES一列会隔一段时间增长0.2M左右,测试发现,使用libCurl库时,有内存没有释放;具体内存增长的原因是因为没有使用curl_slist_free_all(plist);该函数进行释放资源导致。