how to use cookies and postfields with libcurl in C? -
when
curl --get --cookie-jar mycookie.cookie http://mypage/page/
it store cookie mycookie.cookie
and when
curl --cookie mycookie.cookie --data "field1=field1" --data "field2=field2" --data csrfmiddlewaretoken=(csrf token) http://mypage/page/register/
the csrf token
through cat mycookie.cookie
, fill manually in.
this works. want.
so want use libcurl c
this. following doc have this:
curl *curl; curlcode res; curl_global_init(curl_global_all); curl = curl_easy_init(); if (curl) { curl_easy_setopt(curl, curlopt_url, http://mypage/page/); curl_easy_setopt(curl, curlopt_verbose, 1l); curl_easy_setopt(curl, curlopt_cookiefile, ""); res = curl_easy_perform(curl); res = curl_easy_getinfo(curl, curlinfo_cookielist, &cookies); curl_easy_setopt(curl, curlopt_url, http://mypage/page/register/); curl_easy_setopt(curl, curlopt_cookiefile, cookies); curl_easy_setopt(curl, curlopt_postfields, "field1=field1;field1=field1;csrfmiddlewaretoken=(csrf token)"); res = curl_easy_perform(curl); printf("erasing curl's knowledge of cookies!\n"); curl_easy_setopt(curl, curlopt_cookielist, "all"); curl_slist_free_all(cookies); } curl_global_cleanup(); return 0;
so pass cookie throw error missing fields. thought line post fields:
curl_easy_setopt(curl, curlopt_postfields, "field1=field1;field1=field1;csrfmiddlewaretoken=(csrf token)");
i tried passing fields through line:
curl_easy_setopt(curl, curlopt_cookiefile, cookies);
by riding in char array
i tried replacing ,
;
nothing works.
i don't think wrote wrong, looks more post overwrite each other, because if run programm without cookiefile
line says missing cookie.
any idea, how post necessary pieces information?
edit
ok, got work through these 2 posts here , here , daniel stenberg
so have same code without
curl_easy_setopt(curl, curlopt_cookiefile, cookies);
your string sent curlopt_postfields different string command line uses! when use
--data
multiple times, curl concatenate strings ampersand (&) in between, while c code uses semicolon.you pass wrong input curlopt_cookiefile. accepts file name, nothing else. don't need use option in second request, since enabled "cookie engine" in first request, cookies recieved in first request kept in curl handle , used in subsequent request anyway when reusing handle.
to extract
csrf_token
cookie, usecurlinfo_cookielist
, parse through list of cookies find it, extract contents , use in subsequent post request.
Comments
Post a Comment