【发布时间】:2017-10-29 07:00:14
【问题描述】:
我目前正在尝试使用 JSON 正文在 iOS 平台上发出 POST 请求。我的请求在 cURL 中有效,但我无法让它在 iOS 中工作;请求超时。这是我的快速代码:
class func createNewChannel(name: String, priv: String, channelKey: String, handle: String, password: String, auth: String) {
let baseURL = "http://10.0.0.220:3000/"
let dict = ["name": name, "private": priv, "channelKey": channelKey, "handle": handle, "password": password, "auth": auth] as [String : Any]
let jsonData = JSON(dict)
do {
let post = try jsonData.rawData()
let postLength = String(post.count)
let url = URL(string: "\(baseURL)channel/createChannel")!
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.httpBody = post as Data
request.setValue(postLength, forHTTPHeaderField: "Content-Length")
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.setValue("application/json", forHTTPHeaderField: "Accept")
let session = URLSession.shared
let task = session.dataTask(with: request, completionHandler: { (data, response, error) in
if error == nil {
do {
let json = try JSON(data: data!)
print(json)
}
catch {
print(error.localizedDescription)
}
}
else {
print(error!)
}
})
task.resume()
}
catch {
print(error.localizedDescription)
}
}
当我调用此函数时,请求不起作用...我确定我使用的是正确的 url,因为它适用于 GET 端点。我错过了任何标题吗?如果您发现请求有问题,请告诉我。
【问题讨论】: