微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

jsoncpp和curl的使用

#include <stdio.h>
#include <string.h>
#include <curl/curl.h>
#include <json/json.h>
#define MAX_BUF      65536
char wr_buf[MAX_BUF+1];
int  wr_index;
size_t write_data( void *buffer,size_t size,size_t nmemb,void *userp )
{
        int segsize = size * nmemb;
        if ( wr_index + segsize > MAX_BUF ) {
                *(int *)userp = 1;
                return 0;
        }
       
        memcpy( (void *)&wr_buf[wr_index],buffer,(size_t)segsize );
       
        wr_index += segsize;
       
        wr_buf[wr_index] = 0;
       
        return segsize;
}
int main( void )
{
        CURL *curl;
        CURLcode ret;
        int  wr_error;
        wr_error = 0;
        wr_index = 0;
       
        curl = curl_easy_init();
        if (!curl) {
                printf("Couldn't init curl ");
                return 0;
        }
        //指定url
        curl_easy_setopt( curl,CURLOPT_URL,".json" );
        //准备构造json格式消息
        Json::Value root;
		    //根节点属性
			 //子节点
    Json::Value partner;
			    //子节点属性
    partner["channel"] = Json::Value("123333");
    partner["secretKey"] = Json::Value("123");
    root["additional"] = Json::Value(partner);
	 
    root["serviceCode"] = Json::Value("so.g11111");
//   root["params"] = Json::Value("[""8554"," HAIXT" "]");
      root["params"].append("8711111");
      root["params"].append("H111");
//      root["achievement"].append("ach3");
   
 

 
    //子节点挂到根节点上
 //   root["partner"] = Json::Value(partner);

        Json::Reader reader;

        std::string strResult = root.toStyledString();
        Json::Value result;
        //测试构造字符串内容
        if (reader.parse(strResult,result))
        {
                if(!result["id"].isNull())
                {
                        //std::cout<<result["id"].asInt()<<std::endl;
                }
        }
        std::cout<<root.toStyledString().c_str()<<std::endl;
         //设置http请求json格式参数
        curl_easy_setopt(curl,CURLOPT_POSTFIELDS,root.toStyledString().c_str());
        curl_easy_setopt( curl,CURLOPT_WRITEDATA,(void *)&wr_error );
        curl_easy_setopt( curl,CURLOPT_WRITEFUNCTION,write_data );
       
        ret = curl_easy_perform( curl );
        printf( "ret = %d (write_error = %d) ",ret,wr_error );
       
        if ( ret == 0 ) printf( "%s ",wr_buf );
        curl_easy_cleanup( curl );
        return 0;
}

原文地址:https://www.jb51.cc/json/289731.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐