首页 > 学院 > 开发设计 > 正文

C语言典型代码---Curl实现POST

2019-11-08 00:41:17
字体:
来源:转载
供稿:网友

利用CURL库实现post发送

#include "include/curl/curl.h"extern char send_basic_path[URL_LEN];extern char send_running_path[URL_LEN];/*************************************初始化,在程序开始的时候调用*************************************/int sj_curl_init(void){ curl_global_init(CURL_GLOBAL_ALL); return RES_SUCCESS;}/*************************************在程序退出的时候调用*************************************/void sj_curl_end(void){ curl_global_cleanup(); return;}/*************************************回调函数,处理post返回数据的地方*************************************/int sj_curl_post_parse(void* buffer, size_t size, size_t nmemb, char * useless) { char value[BUFSIZE] = {0}; char htvalue[BUFSIZE] = {0}; char *v = NULL; memcpy(value, (char *)buffer, size*nmemb); PRintf("-------%s/n", value); v = strstr(value, "/"data/""); if (NULL != v) { memcpy(htvalue, "{", 1); strcat(htvalue, v); //printf("-------%s/n", htvalue); } else { } return RES_SUCCESS; } /*************************************模拟POST发送*************************************/int sj_curl_post_get(char *send_data, char *url){ CURLcode res; CURL *curl; int iRet = RES_SUCCESS; curl = curl_easy_init(); curl_easy_setopt(curl, CURLOPT_URL, url); //url地址 curl_easy_setopt(curl, CURLOPT_POSTFIELDS, send_data); //post参数 curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, ft_curl_post_parse); //对返回的数据进行操作的函数地址 curl_easy_setopt(curl, CURLOPT_WRITEDATA, NULL); //这是write_data的第四个参数值 curl_easy_setopt(curl, CURLOPT_POST, 1); //设置问非0表示本次操作为post //curl_easy_setopt(curl, CURLOPT_VERBOSE, 1); //打印调试信息 //curl_easy_setopt(g_curl, CURLOPT_HEADER, 1); //将响应头信息和相应体一起传给write_data curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1); //设置为非0,响应头信息location curl_easy_setopt(curl, CURLOPT_COOKIEFILE, "/Users/zhu/CProjects/curlposttest.cookie"); curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1L); curl_easy_setopt(curl, CURLOPT_FORBID_REUSE, 1); curl_easy_setopt(curl, CURLOPT_TIMEOUT, 5L); res = curl_easy_perform(curl); if (res != CURLE_OK) { switch(res) { case CURLE_UNSUPPORTED_PROTOCOL: smart_log(ERROR,"Does not support agreement","FAIL"); break; case CURLE_COULDNT_CONNECT: smart_log(ERROR,"not link remote server","FAIL"); break; case CURLE_HTTP_RETURNED_ERROR: smart_log(ERROR,"http return failed","FAIL"); break; case CURLE_READ_ERROR: smart_log(ERROR,"read local file failed","FAIL"); break; default: smart_log(ERROR,"curl other error","FAIL"); break; } iRet = RES_FAIL; } else { iRet = RES_SUCCESS; } curl_easy_cleanup(curl); return iRet;}
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表