libcurl简单使用

1.发送请求获取数据

 

 1 #include <stdio.h>
 2 #include <stdlib.h>
 3 #include <string.h>
 4 #include <curl/curl.h>
 5  
 6 #define LOGINSTATEURL "URL"
 7 #define REFERERINDEX "Referer: referer url"
 8  
 9 size_t call_back(void* buffer,size_t size,size_t nmemb,void *stream)
10 {
11     char *buf = (char *)stream;
12     strcpy(buf, (char*)buffer);
13     return size*nmemb;
14 }
15  
16 int main(int argc,char *argv[])
17 {
18     int ret = 0;
19     CURL *curl;
20     CURLcode res;
21     struct curl_slist *headers = NULL;
22     char buf[2048] = "";
23     curl = curl_easy_init();
24     if (!curl)
25     {
26         sfw_printf("Failed init login curl\n");
27         return 0;
28     }
29     headers = curl_slist_append(headers,REFERERINDEX);
30     curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
31     curl_easy_setopt(curl,CURLOPT_URL,LOGINSTATEURL);
32     curl_easy_setopt(curl,CURLOPT_POSTFIELDS,""); 
33         
34     curl_easy_setopt(curl,CURLOPT_WRITEFUNCTION,call_back);
35     curl_easy_setopt(curl,CURLOPT_WRITEDATA,&buf); 
36         
37     curl_easy_setopt(curl,CURLOPT_POST,1); 
38     //curl_easy_setopt(curl,CURLOPT_VERBOSE,1); //打印调试信息
39     //curl_easy_setopt(curl,CURLOPT_HEADER,0); //将响应头信息和相应体一起传给call_back
40     curl_easy_setopt(curl,CURLOPT_FOLLOWLOCATION,1); //设置为非0,响应头信息location
41     //curl_easy_setopt(curl,CURLOPT_COOKIEFILE,"/tmp/cookie");//从文件读取cookie
42     curl_easy_setopt(curl,CURLOPT_COOKIE,"cookie str");
43  
44     res = curl_easy_perform(curl);
45     if (res != CURLE_OK)
46     {
47         switch(res)
48         {
49             case CURLE_UNSUPPORTED_PROTOCOL:
50                 fprintf(stderr,"不支持的协议,由URL的头部指定\n");
51             case CURLE_COULDNT_CONNECT:
52                 fprintf(stderr,"不能连接到remote主机或者代理\n");
53             case CURLE_HTTP_RETURNED_ERROR:
54                 fprintf(stderr,"http返回错误\n");
55             case CURLE_READ_ERROR:
56                 fprintf(stderr,"读本地文件错误\n");
57             default:
58                 fprintf(stderr,"返回值:%d\n",res);
59         }
60         return -1;
61     }
62 
63     const char *success_str = "\"success\":true";
64     char *success = strstr(buf, success_str);
65     if (NULL != success)
66     {
67         ret=1;
68     } 
69     else
70     {
71         ret=0;
72     }
73     curl_slist_free_all(headers);
74     curl_easy_cleanup(curl);
75     return ret;76 }

 

posted @ 2020-08-25 16:37  G1733  阅读(555)  评论(0编辑  收藏  举报