简体   繁体   English

在C ++中的函数中使用CURL

[英]Using CURL in function in c++

I'm trying tu use curl in c++ using function. 我正在尝试使用函数在C ++中使用curl。 Example: 例:

#define ...
...
...

/*  CURL parameters */
CURL *curl = curl_easy_init();
CURLcode res;
string readBuffer;

void setHeader(){
    if(curl) {
        /*  Headers */
        struct curl_slist *chunk = NULL;
        chunk = NULL;
        chunk = curl_slist_append(chunk, "Connection:keep-alive");
        ..
        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback);
        curl_easy_setopt(curl, CURLOPT_WRITEDATA, &readBuffer); 
    }    
}

void myFunction1(){
    setHeader();
    curl_easy_setopt(curl, CURLOPT_URL, "....");
    curl_easy_setopt(curl, CURLOPT_COOKIEFILE, cookiePath);
    curl_easy_setopt(curl, CURLOPT_COOKIEJAR, cookiePath);
    res = curl_easy_perform(curl);
    cout << readBuffer;
    curl_easy_cleanup(curl); 
}

void myFunction2(){
    setHeader();
    curl_easy_setopt(curl, CURLOPT_URL, "....");
    curl_easy_setopt(curl, CURLOPT_COOKIEFILE, cookiePath);
    curl_easy_setopt(curl, CURLOPT_COOKIEJAR, cookiePath);
    res = curl_easy_perform(curl);
    cout << readBuffer;
    curl_easy_cleanup(curl);
}

In the main function i call myFunction1 or myFunction2; 在主函数中,我调用myFunction1或myFunction2;

I don't know if is right to use libcurl in this way, but I'm having a problem. 我不知道以这种方式使用libcurl是否正确,但是我遇到了问题。 I use this to login in my site, so I save the cookie whit this code: 我用它来登录我的网站,所以我用以下代码保存cookie:

curl_easy_setopt(curl, CURLOPT_COOKIEFILE, cookiePath);
curl_easy_setopt(curl, CURLOPT_COOKIEJAR, cookiePath);
int main(){
curl_global_init(CURL_GLOBAL_ALL);
myFunction1();
myFunction2();
curl_global_cleanup();
}

Suppose i login and save the cookie in myFunction1. 假设我登录并将cookie保存在myFunction1中。 When I'm trying to set in the myFunction2 it crash on the CURLOPT_COOKIEFILE row. 当我尝试在myFunction2中进行设置时,它在CURLOPT_COOKIEFILE行上崩溃。 I don't know why the cookie is saved in the file, but it can't be used beacuse when I run the program it crash on that row. 我不知道为什么将cookie保存在文件中,但是由于我在运行该程序时崩溃,因此无法使用它。

Sorry for my English Thank's 对不起,我的英语谢谢

The reason of my problem is that when I use the curl_easy_cleanup(curl) and then curl_easy_init I change the sessionID, so the cookie that I've saved are no longer good. 我出现问题的原因是,当我使用curl_easy_cleanup(curl)然后使用curl_easy_init时,我更改了sessionID,因此保存的cookie不再有效。 So I use at the first curl_easy_init, then I make all my request in my functions, and at the end of my program I use curl_easy_cleanup. 因此,我首先使用curl_easy_init,然后在函数中发出所有请求,然后在程序结尾使用curl_easy_cleanup。 To clean the CURL OPTION you can use: curl_easy_reset(). 要清理CURL OPTION,可以使用:curl_easy_reset()。 I've update this post for people that can have my same problem. 我已为可能遇到相同问题的人们更新了此帖子。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM