Sample code for 30+ languages & platforms
Lua

Adding Cookies to an HTTP Request

See more HTTP Examples

Demonstrates how to add one or more cookies to an HTTP request.

Chilkat Lua Downloads

Lua
local chilkat = require("chilkat")

-- This example assumes the Chilkat API to have been previously unlocked.
-- See Global Unlock Sample for sample code.

local http = chilkat.Http.new()

-- The Cookie header field has this format:
-- Cookie: name1=value1 [; name2=value2] ...

-- Build an HTTP POST request:
local req = chilkat.HttpRequest.new()
req:set_from_url("http://www.chilkatsoft.com/echoPost.asp")
req.http_verb = "POST"

req:add_param("param1", "value1")
req:add_param("param2", "value2")

-- To add cookies to any HTTP request sent by a Chilkat HTTP method
-- that uses an HTTP request object, add the cookies to the
-- request object by calling AddHeader.

-- Add two cookies:
req:add_header("Cookie", "user=\"mary\"; city=\"Chicago\"")

-- Send the HTTP POST.
-- (The cookies are sent as part of the HTTP header.)

local domain = "www.chilkatsoft.com"
local port = 80
local ssl = false
local resp = chilkat.HttpResponse.new()
local success = http:http_sreq(domain, port, ssl, req, resp)
if not success then
    print(http.last_error_text)
    return
end

-- Display the HTML body of the response.
if resp.status_code == 200 then
    -- Show the last HTTP request header sent, which should include
    -- our cookies...
    print(http.last_header)
else
    print("HTTP Response Status = " .. resp.status_code)
end

print("---------------------")

-- Some Chilkat HTTP methods do not use an HTTP request object.
-- For these methods, such as for QuickGetStr, cookies (or any HTTP request header)
-- are added by calling SetRequestHeader.
http:set_request_header("Cookie", "user=\"mary\"; city=\"Chicago\"")

local html = http:quick_get_str("http://www.w3.org/")
if not http.last_method_success then
    print(http.last_error_text)
else
    -- Show the last HTTP request header sent, which should include
    -- our cookies...
    print(http.last_header)
end