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

由于Get方式可以直接在浏览器显示的,但是post的json方式不能直接在浏览器,所以这里讲解一下curl的post的json方法

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

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

 JSON格式post方法

[cpp]  view plain copy 在CODE上查看代码片 派生到我的代码片
  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.haxx.se/download.html




以下是c代码的实现:

[cpp]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
#include <stdio.h>   #include <stdlib.h>   #include <string.h>   #include <curl/curl.h>      #define POSTURL    "http://www.xiami.com/member/login"   #define POSTFIELDS "email=myemail@163.com&password=mypassword&autologin=1&submit=登 录&type="   #define FILENAME   "curlposttest.log"      size_t write_data(void *buffer, size_t size, size_t nmemb, void *userp) {
    FILE *fptr = (FILE*)userp;
    fwrite(buffer, size, nmemb, fptr);
    return size * nmemb;//注意这里必须要这样写不然会出错
}
curl de POST 方法
uint64_t curl_post_content (const char * url, char * content)//返回下载数据长度
{
    CURL *curl;
    CURLcode res;
    FILE *fptr;
    struct curl_slist *http_header = NULL;


    if ((fptr = fopen(FILENAME, "w")) == NULL) {
        fprintf(stderr, "fopen file error: %s\n", FILENAME);
        exit(1);
    }


    curl = curl_easy_init();
    curl_easy_setopt(curl, CURLOPT_URL, POSTURL);
    curl_easy_setopt(curl, CURLOPT_POSTFIELDS,"json={\"total\":50.5,\"userId\":12345,\"productId\":1,\"productPrice\":10.1,\"equipmentId\":1,\"productCount\":5,\"productRoughness\":2}");   //设置post属性,使用&来将表单属性连接在一起
    curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data);   //回调函数,可有可无
    curl_easy_setopt(curl, CURLOPT_WRITEDATA, fptr);           //回调函数写入数据指针
    curl_easy_setopt(curl, CURLOPT_POST, 1);                 //设置libcurl发送的协议
    curl_easy_setopt(curl, CURLOPT_VERBOSE, 1);              //设置版本
    curl_easy_setopt(curl, CURLOPT_HEADER, 1);               //设置http数据头
    curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1);       //设置返回的数据量
    curl_easy_setopt(curl, CURLOPT_COOKIEFILE, "curlposttest.cookie");   //设置cookie,不是必须
    res = curl_easy_perform(curl);
    printf("--->>>return is %d\n",res);
    curl_easy_cleanup(curl);
}

欢迎关注并加入物联网行业联盟,积累行业人脉和资源。


  • 1
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值