如何使用 NSURLSession 在 Swift 中定义内容类型 [英] How can I define Content-type in Swift using NSURLSession

查看:22
本文介绍了如何使用 NSURLSession 在 Swift 中定义内容类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to set content-type in my below code to call web api. Content-type will be 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()

推荐答案

如果要设置请求的Content-Type,可以创建自己的URLRequest,提供您的 URL,使用 setValue(_:forHTTPHeaderField:) 指定 Content-Type 标头,然后使用 URLRequest 而不是发出请求URL 直接.只需将 httpBody 设置为该 JSON 并指定 POSThttpMethod:

If you want to set the Content-Type of the request, you can create your own URLRequest, supplying your URL, specify the Content-Type header using setValue(_:forHTTPHeaderField:) and then issue the request with the URLRequest instead of the URL directly. And just set the httpBody to be that JSON and specify the httpMethod of POST:

let url = URL(string: "https://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()

对于 Swift 2 版本,请参阅此答案的先前修订版.

For Swift 2 rendition, see previous revision of this answer.

这篇关于如何使用 NSURLSession 在 Swift 中定义内容类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆