Capturing HTTP Cookies in a POST Response and Sending in Subsequent HTTP POST’s

Question: A particular REST/Web API returns a cookie. I need to capture this cookie and use it when sending subsequent POSTs. For example, this is the CURL statement to login and save the response cookie(s) to a file.

curl -c cookies.txt -H "Content-Type: application/json" -X POST -d '{"username":"user","password":"pass"}' http://192.168.1.1/api/login

Then I need to use the cookie when sending an SMS like this:

curl -b cookies.txt -H "Content-Type: application/json" -X POST -d '{"address":"+88811122222","content":"SMS Content"}' http://192.168.1.1/api/cmd.sms.sendMessage

Do you have a sample code in C that shows how I should do it?

Answer:

With Chilkat, you don’t need to save cookies to a file and then re-send.  You can simply tell Chilkat to cache cookies in memory, and then re-send with subsequent requests.  The cookies cached to memory are specific to the HTTP object instance.   So it’s only a matter of setting a few HTTP object properties:  SaveCookies, SendCookies, and CookieDir. In “C”, setting the properties to automatically cache received cookies in memory and send in subsequent requests looks like this:

HCkHttp http;
http = CkHttp_Create();

// To save cookies to an in-memory cache, set the
// CookieDir equal to "memory". Also,
// set the SaveCookies property:
CkHttp_putCookieDir(http,"memory");
CkHttp_putSaveCookies(http,TRUE);

// To cause cached cookies to be sent with
// subsequent HTTP requests, set the SendCookies
// property = TRUE.
CkHttp_putSendCookies(http,TRUE);

// Any methods that do a GET, POST, etc. will save
// cookies to the CookieDir (which in this case is an
// in-memory cache.

You can use Chilkat’s online tool at https://tools.chilkat.io/curlHttp  to generate the code for each of the above CURL statements.  The online code generator will (currently) ignore the “-c” and “-b” CURL options.  The solution is to add the above lines of code to the generated code.  Of course, set the properties before the code that sends the HTTP request.