curl获得cookie数据
CURL *curl; CURLcode res; struct curl_slist *headers = NULL; curl_global_init(CURL_GLOBAL_ALL); curl = curl_easy_init(); if(curl) { //初始化cookie引擎 curl_easy_setopt(curl,CURLOPT_COOKIEFILE,""); //初始化cookie引擎,才能正确接收到cookie数据. curl_easy_setopt(curl,CURLOPT_FOLLOWLOCATION, 1L); curl_easy_setopt(curl, CURLOPT_URL,"https://passport.csdn.net/account/login"); curl_easy_setopt(curl, CURLOPT_COOKIEJAR, "cookie_open.txt"); //把服务器发过来的cookie保存到cookie_open.txt curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0L); curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0L); //FILE *bodyfile; //bodyfile = fopen("open.html","w"); //curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data); //写数据的回调函数存文件 //curl_easy_setopt(curl,CURLOPT_WRITEDATA, bodyfile); string content; //设置回调函数 curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, writer); curl_easy_setopt(curl, CURLOPT_WRITEDATA, &content); //执行http请求 res = curl_easy_perform(curl); //如果执行成功, if(res == CURLE_OK) { struct curl_slist *cookies = NULL; curl_easy_getinfo(curl,CURLINFO_COOKIELIST,&cookies); //获得cookie数据 int i=1; while (cookies) { TRACE("[%d]: %s ", i, cookies->data); cookies = cookies->next; i++; } } //再次请求的地址 char *token_url="https://passport.csdn.net/account/login"; //释放资源 //fclose(bodyfile); curl_slist_free_all(headers); curl_easy_cleanup(curl); } curl_global_cleanup();
本来我的操作很简单,从传输过来的数据中获得cookie数据就可以了,但必须要执行curl_easy_setopt(curl,CURLOPT_COOKIEFILE,"");才能正确接收到cookie数据.让我很是想不通,我拿我的cookie数据,设置什么cookie的文件?
后来查到官方示例代码:
curl_easy_setopt(curl, CURLOPT_URL, "http://www.example.com/"); curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L); curl_easy_setopt(curl, CURLOPT_COOKIEFILE, ""); /* just to start the cookie engine */ res = curl_easy_perform(curl); if (res != CURLE_OK) { fprintf(stderr, "Curl perform failed: %s ", curl_easy_strerror(res)); return 1; } print_cookies(curl);
CURLOPT_COOKIEFILE后有一句注释just to start the cookie engine.译为"仅仅开始cookie引擎",你运行cookie引擎用个别的方法好不好?否则从CURLOPT_COOKIEFILE上理解就是与cookie的file有关系,太有歧义了.
所以,通过curl获得cookie一定要注意这里.
声明:该文观点仅代表作者本人,牛骨文系教育信息发布平台,牛骨文仅提供信息存储空间服务。
- 上一篇: 使用CURL来获取COOKIE的方法
- 下一篇: curl模拟登陆获取cookie