libcurl之cookie操作

写在最前

C编程需要网页请求时当然首选libcurl库啦,涉及到登录的肯定需要对cookie操作了。所以本文主要是记录一下接收和发送cookie的方法,以及需要注意的地方。

1、发送(往curl导入)cookie的两个方法:

(1)CURLOPT_COOKIELIST
curl_easy_setopt(curl, CURLOPT_COOKIELIST, my_cookie);
这个操作不方便的地方在于要自己组织cookies字符串

(2)CURLOPT_COOKIEFILE
curl_easy_setopt(curl, CURLOPT_COOKIEFILE, “cookies.txt”);
而cookie.txt中的cookies是由下面说到的CURLOPT_COOKIEJAR操作得到的。

PS:两个方法在导入时间上还有一点不同之处:
CURLOPT_COOKIELIST:my_cookie is imported immediately via CURLOPT_COOKIELIST.
CURLOPT_COOKIEFILE:The list of cookies in cookies.txt will not be imported until right before a transfer is performed.
更多不同详见官网说明

2、获取(从curl导出)cookie的方法:

curl_easy_setopt(curl, CURLOPT_COOKIEJAR, “cookies.txt”);
所以CURLOPT_COOKIEJAR与CURLOPT_COOKIEFILE配合使用还是很方便的。

注意
导出操作(CURLOPT_COOKIEJAR)是在调用curl_easy_cleanup之后。官网原话"Cookies are exported after curl_easy_cleanup is called."
这其实没什么,但就被我撞上了。昨天删除部分打印的时候不小心(dd操作变成d+方向键下,vim党)把·curl_easy_cleanup·删除了,结果发现在下次请求时一直返回失败,最后发现cookies.txt文件不存在导致请求没有带上cookies,这才发现问题所在(大大一个囧)

以下是官网的EXAMPLE:

/* This example shows an inline import of a cookie in Netscape format.
You can set the cookie as HttpOnly to prevent XSS attacks by prepending
#HttpOnly_ to the hostname. That may be useful if the cookie will later
be imported by a browser.
*/

#define SEP  "\t"  /* Tab separates the fields */

char *my_cookie =
  "example.com"    /* Hostname */
  SEP "FALSE"      /* Include subdomains */
  SEP "/"          /* Path */
  SEP "FALSE"      /* Secure */
  SEP "0"          /* Expiry in epoch time format. 0 == Session */
  SEP "foo"        /* Name */
  SEP "bar";       /* Value */

/* my_cookie is imported immediately via CURLOPT_COOKIELIST.
*/
curl_easy_setopt(curl, CURLOPT_COOKIELIST, my_cookie);

/* The list of cookies in cookies.txt will not be imported until right
before a transfer is performed. Cookies in the list that have the same
hostname, path and name as in my_cookie are skipped. That is because
libcurl has already imported my_cookie and it's considered a "live"
cookie. A live cookie won't be replaced by one read from a file.
*/
curl_easy_setopt(curl, CURLOPT_COOKIEFILE, "cookies.txt");  /* import */

/* Cookies are exported after curl_easy_cleanup is called. The server
may have added, deleted or modified cookies by then. The cookies that
were skipped on import are not exported.
*/
curl_easy_setopt(curl, CURLOPT_COOKIEJAR, "cookies.txt");  /* export */

curl_easy_perform(curl);  /* cookies imported from cookies.txt */

curl_easy_cleanup(curl);  /* cookies exported to cookies.txt */

from: https://curl.haxx.se/libcurl/c/CURLOPT_COOKIELIST.html

你可能感兴趣的:(web)