我目前正在尝试使用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端点。我错过任何标题吗?如果您发现请求有问题,请告诉我。
答案 0 :(得分:2)
我只想自己发布一个答案,因为它可能会帮助将来的某个人。我正在使用设备发出请求,我正在向localhost发出请求。我太笨了,无法在手机上关闭无线网络.....
答案 1 :(得分:1)
请试一试。
let session = URLSession.shared
let request = URLRequest(url:url)
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.httpMethod = "POST"
do {
let data = try JSONSerialization.data(withJSONObject: yourParam!, options:JSONSerialization.WritingOptions(rawValue: 0))
let mappedString : String = (String(data: data , encoding: String.Encoding.utf8)!)
request.httpBody = mappedString.data(using: String.Encoding.utf8, allowLossyConversion: false)
}
catch let error as NSError
{
print("JSON ERROR 1 " + error.localizedDescription)
closure(Result.failure(error))
return
}
let task = session.dataTask(with: request, completionHandler: {
(data, response, error) in
DispatchQueue.main.async {
guard data != nil && error == nil else {
print(error)
return
}
do {
let jsonResult : NSDictionary? = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.mutableContainers) as? NSDictionary
print("jsonResult\(jsonResult!)")
} catch let error as NSError {
print("JSON ERROR 2 " + error.localizedDescription)
}
}
})
task.resume()
感谢。