curl如何处理cookie: curl的easy接口中提供了5个与cookie有关的option,其中,CURLOPT_COOKIEFILE,CURLOPT_COOKIEJAR,CURLOPT_COOKIELIST都会打开curl的cookie引擎,使得curl在收到http response时解析header field中的cookie。 设置 CURLOPT_COOKIEFILE 会使curl下一次发请求时从指定的文件中读取cookie。 设置 CURLOPT_COOKIEJAR 会使curl在调用 curl_easy_cleanup的时候把cookie保存到指定的文件中。 设置CURLOPT_COOKIELIST会把指定的cookie字符串列表加入easy handle维护的cookie列表中。每个cookie字符串要么符合HTTP response header的"Set-Cookie: NAME=VALUE;..."格式,要么符合Netscape cookie格式。 CURLOPT_COOKIE用于设置一个分号分隔的“NAME=VALUE”列表,用于在HTTP request header中设置Cookie header。 curl内部使用Cookie和CookieInfo两个struct保存cookie信息。 为一个easy handle设置 CURLOPT_SHARE 选项,并且指定的share handle启用了cookie共享功能, 则easy handle会使用share handle中的共享cookie列表。 例如: int PostUrlchar* url, void *savepath) { // 初始化libcurl CURLcode return_code; return_code = curl_global_init(CURL_GLOBAL_WIN32); if (CURLE_OK != return_code) return 0; CURL *curl_handle; CURLcode res; curl_handle = curl_easy_init(); curl_easy_setopt(curl_handle, CURLOPT_URL, url); curl_easy_setopt(curl_handle, CURLOPT_FOLLOWLOCATION, true); curl_easy_setopt(curl_handle, CURLOPT_USERAGENT,"Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.9.2.8) Gecko/20100722 Firefox/3.6.8"); curl_easy_setopt(curl_handle, CURLOPT_COOKIEJAR, "cookie.txt"); curl_easy_setopt(curl_handle, CURLOPT_COOKIEFILE, "cookie.txt"); curl_easy_setopt(curl_handle, CURLOPT_WRITEFUNCTION, write_callback); curl_easy_setopt( curl_handle, CURLOPT_WRITEDATA, savepath ); curl_easy_setopt(curl_handle, CURLOPT_POSTFIELDS,postLoginData); res = curl_easy_perform(curl_handle); curl_easy_cleanup(curl_handle); curl_global_cleanup(); if (res == CURLE_OK) { return 1; } return 0; } int GetUrl(string url,void *buffer) { // 初始化libcurl CURLcode return_code; return_code = curl_global_init(CURL_GLOBAL_WIN32); if (CURLE_OK != return_code) return 0; CURL *easy_handle = curl_easy_init(); if (NULL == easy_handle) { curl_global_cleanup(); return 0; } // 设置easy handle属性 curl_easy_setopt(easy_handle, CURLOPT_USERAGENT,"Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.9.2.8) Gecko/20100722 Firefox/3.6.8"); curl_easy_setopt(easy_handle,CURLOPT_FOLLOWLOCATION,TRUE); curl_easy_setopt(easy_handle, CURLOPT_URL, url.c_str()); curl_easy_setopt(easy_handle, CURLOPT_WRITEFUNCTION, write_callback); curl_easy_setopt(easy_handle, CURLOPT_WRITEDATA, buffer); curl_easy_setopt(easy_handle, CURLOPT_COOKIEFILE,"cookie.txt"); curl_easy_setopt(easy_handle, CURLOPT_COOKIEJAR, "cookie.txt"); curl_easy_perform(easy_handle); curl_easy_cleanup(easy_handle); curl_global_cleanup(); return 1; }