gpt4 book ai didi

web-services - 如何使用 NSURLSession 在 Swift 中定义内容类型

转载 作者:IT王子 更新时间:2023-10-29 05:15:10 24 4
gpt4 key购买 nike

我想在下面的代码中设置内容类型来调用 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()

最佳答案

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

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 版本,请参阅 previous revision of this answer .

关于web-services - 如何使用 NSURLSession 在 Swift 中定义内容类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27041654/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com