分享

使用curl库,以post方式向服务器发送json数据

 dwlinux_gs 2015-06-26

//使用curl库,以post方式向服务器发送json数据
//json数据的组合可以参考jsoncpp库,也可以按json格式自己组合字符串

//注意事项,以下代码不可以多线程执行,如果多线程执行,需要加锁进行控制,否则会运行崩溃

 

  1. #include <curl/curl.h>  
  2. #include <string>  
  3. #include <exception>  
  4.   
  5. int main(int argc, char *argv[])   
  6. {  
  7.     char szJsonData[1024];  
  8.     memset(szJsonData, 0, sizeof(szJsonData));  
  9.     std::string strJson = "{";  
  10.     strJson += "\"user_name\" : \"test\",";  
  11.     strJson += "\"password\" : \"test123\"";  
  12.     strJson += "}";  
  13.     strcpy(szJsonData, strJson.c_str());  
  14.     try   
  15.     {  
  16.         CURL *pCurl = NULL;  
  17.         CURLcode res;  
  18.         // In windows, this will init the winsock stuff  
  19.         curl_global_init(CURL_GLOBAL_ALL);  
  20.   
  21.         // get a curl handle  
  22.         pCurl = curl_easy_init();  
  23.         if (NULL != pCurl)   
  24.         {  
  25.             // 设置超时时间为1秒  
  26.             curl_easy_setopt(pCurl, CURLOPT_TIMEOUT, 1);  
  27.   
  28.             // First set the URL that is about to receive our POST.   
  29.             // This URL can just as well be a   
  30.             // https:// URL if that is what should receive the data.  
  31.             curl_easy_setopt(pCurl, CURLOPT_URL, "http://192.168.0.2/posttest.svc");  
  32.             //curl_easy_setopt(pCurl, CURLOPT_URL, "http://192.168.0.2/posttest.cgi");  
  33.   
  34.             // 设置http发送的内容类型为JSON  
  35.             curl_slist *plist = curl_slist_append(NULL,   
  36.                 "Content-Type:application/json;charset=UTF-8");  
  37.             curl_easy_setopt(pCurl, CURLOPT_HTTPHEADER, plist);  
  38.   
  39.             // 设置要POST的JSON数据  
  40.             curl_easy_setopt(pCurl, CURLOPT_POSTFIELDS, szJsonData);  
  41.   
  42.             // Perform the request, res will get the return code   
  43.             res = curl_easy_perform(pCurl);  
  44.             // Check for errors  
  45.             if (res != CURLE_OK)   
  46.             {  
  47.                 printf("curl_easy_perform() failed:%s\n", curl_easy_strerror(res));  
  48.             }  
  49.             // always cleanup  
  50.             curl_easy_cleanup(pCurl);  
  51.         }  
  52.         curl_global_cleanup();  
  53.     }  
  54.     catch (std::exception &ex)  
  55.     {  
  56.         printf("curl exception %s.\n", ex.what());  
  57.     }  
  58.     return 0;  
  59. }  

 

参考文档curl压缩包\docs\examples\http-post.c

curl压缩包下载地址:http://curl./download.html


  

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约