zoukankan      html  css  js  c++  java
  • 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
    ");
    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的头部指定
    ");
    51             case CURLE_COULDNT_CONNECT:
    52                 fprintf(stderr,"不能连接到remote主机或者代理
    ");
    53             case CURLE_HTTP_RETURNED_ERROR:
    54                 fprintf(stderr,"http返回错误
    ");
    55             case CURLE_READ_ERROR:
    56                 fprintf(stderr,"读本地文件错误
    ");
    57             default:
    58                 fprintf(stderr,"返回值:%d
    ",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 }
  • 相关阅读:
    四则运算
    四则运算二
    学习进度条
    四则运算一
    课堂测试七
    问题与思考6
    问题与思考5
    问题与思考04
    Android SDK 目录说明
    如何判断视频的比例(4:3/16:9)和分辨率?
  • 原文地址:https://www.cnblogs.com/shiqi17/p/13560487.html
Copyright © 2011-2022 走看看