研究了一下curl操作cookie的方法,有个需要注意的地方:
void BsuHttp::httpGet(const char *url,size_t(*func)(uint8_t *buffer,size_t size,size_t nmemb,void *stream))
{
CURL *curl;
CURLcode res;
char buffer[10];
curl = curl_easy_init(); //对curl进行初始化
if(curl)
{
curl_easy_setopt(curl,CURLOPT_URL,url); //设置url
curl_easy_setopt(curl,CURLOPT_COOKIE,cookie); //设置cookie
curl_easy_setopt(curl,CURLOPT_WRITEFUNCTION,func); //设置接收数据完成后执行的函数
curl_easy_setopt(curl,CURLOPT_COOKIEFILE,""); //设置cookie文件保存路径,必须要执行,否则不能获得cookie数据.
curl_easy_perform(curl); //执行访问地址
struct curl_slist *cookies = NULL;
curl_easy_getinfo(curl,CURLINFO_COOKIELIST,&cookies); //获得cookie数据
int i=1;
while (cookies) {
CCLOG("[%d]: %s\n", i, cookies->data);
cookies = cookies->next;
i++;
}
curl_easy_cleanup(curl); //清理curl对象
}
}
本来我的操作很简单,从传输过来的数据中获得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一定要注意这里.