1、用下面的代码如果服务器返回数据较大的话无法全部接收:
#include <stdio.h> #include <curl/curl.h> #include <stdlib.h> #include<string.h> #include <sys/types.h> #include <json/json.h> #include<string> size_t saveData(void *ptr, size_t size, size_t nmemb, void *userdata) { sprintf((char *)userdata,"%s",(char *)ptr); } int main(int argc, char *argv[]) { CURL *curl; CURLcode res; // char data[]="{\"method\" : \"xbmc_get_dir\",\"para\" : \"?mode=1&name= %E7%94%B5%E8%A7%86%E5%89%A7&id=c_97&cat=%E4%B8%8D%E9%99%90&area=%E4%B8%8D%E9%99%90&year= %E4%B8%8D%E9%99%90&order=7\"}"; //char data[]="{\"method\" : \"xbmc_get_dir\",\"para\" : \"\"}"; json_object *p_json_obj = NULL; p_json_obj = json_tokener_parse(data); int len; curl = curl_easy_init(); char rece[20480]; if(curl!=NULL) { curl_easy_setopt(curl, CURLOPT_POST, 1L); curl_easy_setopt(curl, CURLOPT_URL, "127.0.0.1/xbmc-server.php"); curl_easy_setopt(curl, CURLOPT_POSTFIELDS, data); curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, strlen(data)); curl_easy_setopt(curl, CURLOPT_WRITEDATA, rece); curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, saveData); res = curl_easy_perform(curl); curl_easy_cleanup(curl); } printf("111%s\n",rece); json_object *p_json_obj1 = NULL; p_json_obj1 = json_tokener_parse(rece); json_object *p_obj = json_object_object_get(p_json_obj1, "dirlist"); char * p_method; p_method = (char *)json_object_get_string(p_obj); printf("%s\n",p_method); return 0; }
#include <stdio.h> #include <curl/curl.h> #include <stdlib.h> #include<string.h> #include <sys/types.h> #include <json/json.h> #include<string> std::string strrr; size_t saveData(void *ptr, size_t size, size_t nmemb, void *userdata) { char httpsBuffer[10240]; printf("22222222%s\n",userdata); printf("3333333%s\n\n\n\n",ptr); memset (httpsBuffer,0,sizeof(httpsBuffer)); memcpy(httpsBuffer,ptr,nmemb); std::string tmp((char *)httpsBuffer); strrr+=tmp; return nmemb*size; } int main(int argc, char *argv[]) { CURL *curl; CURLcode res; // char data[]="{\"method\" : \"xbmc_get_dir\",\"para\" : \"?mode=1&name= %E7%94%B5%E8%A7%86%E5%89%A7&id=c_97&cat=%E4%B8%8D%E9%99%90&area=%E4%B8%8D%E9%99%90&year= %E4%B8%8D%E9%99%90&order=7\"}"; json_object *p_json_obj = NULL; p_json_obj = json_tokener_parse(data); int len; curl = curl_easy_init(); char rece[20480]; if(curl!=NULL) { curl_easy_setopt(curl, CURLOPT_POST, 1L); curl_easy_setopt(curl, CURLOPT_URL, "127.0.0.1/xbmc-server.php"); curl_easy_setopt(curl, CURLOPT_POSTFIELDS, data); curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, strlen(data)); curl_easy_setopt(curl, CURLOPT_WRITEDATA, rece); curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, saveData); res = curl_easy_perform(curl); curl_easy_cleanup(curl); } printf("000%s\n",strrr.c_str()); json_object *p_json_obj1 = NULL; p_json_obj1 = json_tokener_parse(strrr.c_str()); json_object *p_obj = json_object_object_get(p_json_obj1, "dirlist"); char * p_method; p_method = (char *)json_object_get_string(p_obj); printf("%s\n",p_method); return 0; }