Swift
Swift
Adding Cookies to an HTTP Request
See more HTTP Examples
Demonstrates how to add one or more cookies to an HTTP request.Chilkat Swift Downloads
func chilkatTest() {
var success: Bool = false
// This example assumes the Chilkat API to have been previously unlocked.
// See Global Unlock Sample for sample code.
let http = CkoHttp()!
// The Cookie header field has this format:
// Cookie: name1=value1 [; name2=value2] ...
// Build an HTTP POST request:
let req = CkoHttpRequest()!
req.set(fromUrl: "http://www.chilkatsoft.com/echoPost.asp")
req.httpVerb = "POST"
req.addParam(name: "param1", value: "value1")
req.addParam(name: "param2", value: "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.addHeader(name: "Cookie", value: "user=\"mary\"; city=\"Chicago\"")
// Send the HTTP POST.
// (The cookies are sent as part of the HTTP header.)
var domain: String? = "www.chilkatsoft.com"
var port: Int = 80
var ssl: Bool = false
let resp = CkoHttpResponse()!
success = http.httpSReq(domain: domain, port: port, ssl: ssl, request: req, response: resp)
if success == false {
print("\(http.lastErrorText!)")
return
}
// Display the HTML body of the response.
if resp.statusCode.intValue == 200 {
// Show the last HTTP request header sent, which should include
// our cookies...
print("\(http.lastHeader!)")
}
else {
print("HTTP Response Status = \(resp.statusCode.intValue)")
}
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.setRequestHeader(name: "Cookie", value: "user=\"mary\"; city=\"Chicago\"")
var html: String? = http.quickGetStr(url: "http://www.w3.org/")
if http.lastMethodSuccess != true {
print("\(http.lastErrorText!)")
}
else {
// Show the last HTTP request header sent, which should include
// our cookies...
print("\(http.lastHeader!)")
}
}