如何使用NSURLSession在Swift中定义Content-type

dha*_*hah 17 web-services swift

我想在下面的代码中设置内容类型来调用web api.内容类型将是 application/json; charset=utf-8

let url = NSURL(string: "http:/api/jobmanagement/PlusContactAuthentication?email=\(usr)&userPwd=\(pwdCode)")

println("URL:  \(url)")

let task = NSURLSession.sharedSession().dataTaskWithURL(url!) {
    (data, response, error) in
    println(NSString(data: data, encoding: NSUTF8StringEncoding))
}

//  task.setValue(<#value: AnyObject?#>, forKey: <#String#>)
task.resume()
Run Code Online (Sandbox Code Playgroud)

Rob*_*Rob 47

如果要设置Content-Type请求,可以创建自己URLRequest的URL,提供URL,指定Content-Type标题setValue(_:forHTTPHeaderField:),然后发出请求,URLRequest而不是URL.因此,在Swift 2中,您可以将其设置为httpBodyJSON并指定它是POST请求:

let url = URL(string: "http:/api/jobmanagement/PlusContactAuthentication")!
var request = URLRequest(url: url)
request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")  // the request is JSON
request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Accept")        // the expected response is also JSON
request.httpMethod = "POST"

let dictionary = ["email": username, "userPwd": password]
request.httpBody = try! JSONEncoder().encode(dictionary)

let task = URLSession.shared.dataTask(with: request) { data, response, error in
    guard let data = data, error == nil else {
        print(error ?? "Unknown error")                                 // handle network error
        return
    }

    // parse response; for example, if JSON, define `Decodable` struct `ResponseObject` and then do:
    //
    // do {
    //     let responseObject = try JSONDecoder().decode(ResponseObject.self, from: data)
    //     print(responseObject)
    // } catch let parseError {
    //     print(parseError)
    //     print(String(data: data, encoding: .utf8))   // often the `data` contains informative description of the nature of the error, so let's look at that, too
    // }
}
task.resume()
Run Code Online (Sandbox Code Playgroud)

在Swift 3中,等效代码是:

let url = URL(string: "http:/api/jobmanagement/PlusContactAuthentication")!
var request = URLRequest(url: url)
request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")  // the request is JSON
request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Accept")        // the expected response is also JSON
request.httpMethod = "POST"

let dictionary = ["email": username, "userPwd": password]
request.httpBody = try! JSONEncoder().encode(dictionary)

let task = URLSession.shared.dataTask(with: request) { data, response, error in
    guard let data = data, error == nil else {
        print(error ?? "Unknown error")                                 // handle network error
        return
    }

    // parse response; for example, if JSON, define `Decodable` struct `ResponseObject` and then do:
    //
    // do {
    //     let responseObject = try JSONDecoder().decode(ResponseObject.self, from: data)
    //     print(responseObject)
    // } catch let parseError {
    //     print(parseError)
    //     print(String(data: data, encoding: .utf8))   // often the `data` contains informative description of the nature of the error, so let's look at that, too
    // }
}
task.resume()
Run Code Online (Sandbox Code Playgroud)