struct MemoryStruct { char *memory; // 指向开辟的空间 size_t size; // 接收到的数据大小 }; // 请求发送后的回调函数,将接收到的消息放在动态开辟的空间内,chunk的memory指针指向它。 static size_t WriteMemoryCallback(void *contents, size_t size, size_t nmemb, void *userp) { size_t realsize = size * nmemb; struct MemoryStruct *mem = (struct MemoryStruct*) userp; mem->memory = realloc(mem->memory, mem->size + realsize + 1); if (mem->memory == NULL) { printf("空间开辟失败\n"); return 0; } memcpy(&(mem->memory[mem->size]), contents, realsize); mem->size += realsize; mem->memory[mem->size] = 0; // printf("%s", mem->memory); return realsize; } // 请求数据,存放在chunk.memory里面,动态分配的 // url: 指向网址字符串的指针 // data: 指向post参数字符串的指针 int httpspost(char *url, char *data, struct MemoryStruct *chunk) { chunk->size = 0; // 清空上一次接受数据的长度 CURL *curl = NULL; CURLcode res; curl_global_init(CURL_GLOBAL_ALL); /* get a curl handle */ curl = curl_easy_init(); if (!curl) { return -1; } /*设置easy handle属性*/ /* specify URL */ curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "POST"); // 设置URL curl_easy_setopt(curl, CURLOPT_URL, url); // 添加参数 curl_easy_setopt(curl, CURLOPT_POSTFIELDS, data); // 设置回调函数 curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteMemoryCallback); // post请求json传参必带 struct curl_slist* headers = NULL; // headers = curl_slist_append(headers, "Content-Type:application/json;charset=UTF-8"); headers = curl_slist_append(headers, "Content-Type:application/x-www-form-urlencoded"); curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers); curl_easy_setopt(curl, CURLOPT_POST, 1); //设置为非0表示本次操作为POST curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void *)chunk); /* set commom option */ curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0L); curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0L); /*执行数据请求*/ res = curl_easy_perform(curl); if (res != CURLE_OK) { fprintf(stderr, "res=%d curl_easy_perform() failed: %s\n", res,curl_easy_strerror(res)); } curl_easy_cleanup(curl); curl_global_cleanup(); return 0; }