libCurl 简单使用

curl easy  的使用步骤

curl_easy_init()

curl_easy_setopt()

curl_easy_perform()

curl_easy_cleanup()

 

------------------------------

//http 返回数据回调

static size_t OnWriteData(void* buffer, size_t size, size_t nmemb, void* lpVoid)  
{  
    std::string* str = dynamic_cast<std::string*>((std::string *)lpVoid);  
    if( NULL == str || NULL == buffer )  
    {  
        return -1;  
    }  

    char* pData = (char*)buffer;  
    str->append(pData, size * nmemb);  
    return nmemb;  
}  

 

1 post 指定的参数到对应的php页面

  CURL *curl;  
    CURLcode res;
  std::string strResponse; curl
= curl_easy_init(); if ( !curl ) { printf("1\n"); return -1; } curl_easy_setopt( curl , CURLOPT_URL ,"http://xxxy.com/xxx.php" ); curl_easy_setopt( curl , CURLOPT_VERBOSE , 1 ) ; curl_easy_setopt( curl , CURLOPT_POSTFIELDS , "value1=123&value2=345" ); //php服务器页面可以 echo $_POST["value1"]; 输出对应的值
   curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, OnWriteData);
   curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void *)&strResponse); 
    res = curl_easy_perform(curl);  
    if ( res != CURLE_OK )  
    {  
        printf("error\n");  
        return -1;  
    }  
    curl_easy_cleanup(curl);  

 

2 以表单方式提交数据,上传文件,

char * desUrl = "127.0.0.1/upload.php";

    const char *filePath = "D://110440.jpg"; //文件全路径

    std::string strResponse;
    CURL *curl;
    CURLcode res;

    struct curl_httppost *formpost=NULL;
    struct curl_httppost *lastptr=NULL;

    curl_global_init(CURL_GLOBAL_ALL);
    
  /*文件上传表单域填写 */ 
    curl_formadd(&formpost,
    &lastptr,
    CURLFORM_COPYNAME, "file",  //php 端用 $_FILES["file"]取得文件信息
    CURLFORM_FILE, filePath,
    CURLFORM_END);

  /* 表单域填写 */ 
    curl_formadd(&formpost,
        &lastptr,
        CURLFORM_COPYNAME, "value1", //php端用$_POST["value1"] 取得对应值
        CURLFORM_COPYCONTENTS, "123",
        CURLFORM_END);

    curl = curl_easy_init();

    if(curl) {

    curl_easy_setopt( curl , CURLOPT_URL ,desUrl );  
    curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, OnWriteData);  
    curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void *)&strResponse); 
    curl_easy_setopt(curl, CURLOPT_POST,1);
    curl_easy_setopt(curl, CURLOPT_HTTPPOST, formpost);

    res = curl_easy_perform(curl);
    if(res != CURLE_OK)
        fprintf(stderr, "curl_easy_perform() failed: %s\n",
                curl_easy_strerror(res));

    /* always cleanup */ 
    curl_easy_cleanup(curl);
/* then cleanup the formpost chain */ curl_formfree(formpost);

 

 

posted on 2014-05-28 15:50  110440  阅读(358)  评论(0编辑  收藏  举报

导航