Adding Headers to Post URL Session DataTask L4.5.1
We can add headers to a NSMutableURLRequest
by storing the headers we want to include in a dictionary and assigning them to the allHTTPHeaderFields
attribute of our request.
Note that to add headers we need to use the mutable form of the request object.
import Foundation
let headers = ["content-type": "application/json;charset=utf-8"]
let parameters = [
"media_type": "movie",
"media_id": 550,
"favorite": true
]
let postData = NSJSONSerialization.dataWithJSONObject(parameters, options: nil, error: nil)
var request = NSMutableURLRequest(URL: NSURL(string: "https://api.themoviedb.org/3/account/%7Baccount_id%7D/favorite?api_key=a14211847de8c0f8d9f4cd9d63f5fc6a")!,
cachePolicy: .UseProtocolCachePolicy,
timeoutInterval: 10.0)
request.HTTPMethod = "POST"
request.allHTTPHeaderFields = headers
request.HTTPBody = postData
let session = NSURLSession.sharedSession()
let dataTask = session.dataTaskWithRequest(request, completionHandler: { (data, response, error) -> Void in
if (error != nil) {
println(error)
} else {
let httpResponse = response as? NSHTTPURLResponse
println(httpResponse)
}
})
dataTask.resume()
Found at The Movie Database API
Some Possible Headers We Can Include
Full list on wikipedia
- Authentication — Content-Types that are acceptable for the response. (
Accept: text/plain
) - Accept-Charset — Character sets that are acceptable. (
Accept-Charset: utf-8
) - Accept-Encoding — List of acceptable encodings. (
Accept-Encoding: gzip, deflate
) - Accept-Language — List of acceptable human languages for response. (
Accept-Language: en-US
) - Authorization - Authentication credentials for HTTP authentication. (
Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==
) - Cookie - An HTTP cookie previously sent by the server with Set-Cookie. (
Cookie: $Version=1; Skin=new;
) - Content-Length — The length of the request body in octets (8-bit bytes). (
Content-Length: 348
) - Proxy-Authorization — Authorization credentials for connecting to a proxy. (
Proxy-Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==
)