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\n", 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();


研究了一下curl操作cookie的方法,有个需要注意的地方:

        本来我的操作很简单,从传输过来的数据中获得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\n", 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一定要注意这里.



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值