本文共 2878 字,大约阅读时间需要 9 分钟。
c++使用libcurl:
1 /* 2 *g++ demo.cpp -g -Wall -lcurl 3 */ 4 5 #include6 #include 7 #include 8 #include 9 #include 10 11 int getUrl(const char* filename) 12 { 13 CURL* curl; 14 CURLcode res; 15 FILE* fp; 16 if((fp=fopen(filename, "w"))==NULL){ 17 return -1; 18 } 19 struct curl_slist *headers = NULL; 20 headers = curl_slist_append(headers, "Accept:Agent-007"); 21 curl = curl_easy_init(); 22 if(curl){ 23 curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers); 24 curl_easy_setopt(curl, CURLOPT_URL, "http://www.baidu.com"); 25 curl_easy_setopt(curl, CURLOPT_WRITEDATA, fp); 26 curl_easy_setopt(curl, CURLOPT_HEADERDATA, fp); 27 28 //0: success, other: failure 29 res = curl_easy_perform(curl); 30 if(res != 0){ 31 std::cout <<"error:"< << std::endl; 32 } 33 curl_slist_free_all(headers); 34 curl_easy_cleanup(curl); 35 fclose(fp); 36 } 37 return res; 38 } 39 40 /* 41 int postUrl(const char* filename) 42 { 43 CURL* curl; 44 CURLcode res; 45 FILE* fp; 46 47 if((fp=fopen(filename, "w"))==NULL){ 48 return 1; 49 } 50 curl = curl_easy_init(); 51 if(curl){ 52 53 } 54 } 55 */ 56 57 //typedef int (* func)(int, int); 58 typedef size_t (*cb_func)(void*, size_t, size_t, void*); 59 size_t write_data(void *buffer, size_t size, size_t nmemb, void *userp) { 60 FILE *fptr = (FILE*)userp; 61 fwrite(buffer, size, nmemb, fptr); 62 return size*nmemb; 63 } 64 65 int PostData(const char* postdata, const char* url, 66 cb_func write_data, void* fptr) 67 //int PostData(const char* postdata, const char* url) 68 { 69 CURL* curl = NULL; 70 CURLcode res; 71 char tmp[32] = { 0}; 72 struct curl_slist* headers = NULL; 73 if(!url){ 74 return -1; 75 } 76 std::cout <<"send data url:" << url << std::endl; 77 snprintf(tmp, sizeof(tmp), "Content-Length: %d", (int)strlen(postdata)); 78 std::cout <<"Content-Length: " << tmp << std::endl; 79 headers = curl_slist_append(headers, "Accept: application/json"); 80 headers = curl_slist_append(headers, "Content-Type: application/json"); 81 headers = curl_slist_append(headers, "charset: utf-8"); 82 headers = curl_slist_append(headers, tmp); 83 84 curl_global_init(CURL_GLOBAL_ALL); 85 curl = curl_easy_init(); 86 if(curl){ 87 curl_easy_setopt(curl, CURLOPT_URL,url); 88 curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers); 89 curl_easy_setopt(curl, CURLOPT_TIMEOUT, 1); //超时时间1s 90 curl_easy_setopt(curl, CURLOPT_POST, 1L); 91 curl_easy_setopt(curl, CURLOPT_POSTFIELDS, postdata); 92 curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data); 93 curl_easy_setopt(curl, CURLOPT_WRITEDATA, fptr); 94 //curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L); //debug 95 res = curl_easy_perform(curl); 96 if(res!=0){ 97 std::cout<<"error no:"< <
转载地址:http://fkudl.baihongyu.com/