1 /*
2 *g++ demo.cpp -g -Wall -lcurl3 */
4
5 #include
6 #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 <
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 <
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<
108 intmain()109 {110 const char* tt = "./aa.out";111 int aa =getUrl(tt);112 std::cout << "return :" << aa <<:endl file if std::cout open error exit>
119 const char* jsondata = "{\"usrname\": \"cp\", \"passwd\": \"test\"}";120 const char* url = "http://192.168.2.163:8080/mystorage/mytest.php";121 aa =PostData(jsondata, url, write_data, fptr);122 return 0;123 }