如何使用 swift 2.0 制作 http post json 请求参数
Posted
技术标签:
【中文标题】如何使用 swift 2.0 制作 http post json 请求参数【英文标题】:how to make http post json request params using swift 2.0 【发布时间】:2016-02-23 06:51:01 【问题描述】:我需要在swift2.0中使用nsurl会话将json请求参数发送到服务器。我不知道如何创建 json 请求参数。我创建了这样的参数
让 jsonObj = ["Username":"Admin", "Password":"123","DeviceId":"87878"]
// print("Params are \(jsonObj)")
//request.HTTPBody = try! NSJSONSerialization.dataWithJSONObject(jsonObj, options: [])
// or if you think the conversion might actually fail (which is unlikely if you built `params` yourself)
do
request.HTTPBody = try NSJSONSerialization.dataWithJSONObject(jsonObj, options:.PrettyPrinted)
catch
print(error)
但它没有 ping 到方法体,所以我得到了失败响应
【问题讨论】:
【参考方案1】:试试下面的代码。
let parameters = ["Username":"Admin", "Password":"123","DeviceId":"87878"] as Dictionary<String, String>
let request = NSMutableURLRequest(URL: NSURL(string:YOURURL)!)
let session = NSURLSession.sharedSession()
request.HTTPMethod = "POST"
//Note : Add the corresponding "Content-Type" and "Accept" header. In this example I had used the application/json.
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
request.HTTPBody = try! NSJSONSerialization.dataWithJSONObject(parameters, options: [])
let task = session.dataTaskWithRequest(request) data, response, error in
guard data != nil else
print("no data found: \(error)")
return
do
if let json = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? NSDictionary
print("Response: \(json)")
else
let jsonStr = NSString(data: data!, encoding: NSUTF8StringEncoding)// No error thrown, but not NSDictionary
print("Error could not parse JSON: \(jsonStr)")
catch let parseError
print(parseError)// Log the error thrown by `JSONObjectWithData`
let jsonStr = NSString(data: data!, encoding: NSUTF8StringEncoding)
print("Error could not parse JSON: '\(jsonStr)'")
task.resume()
希望对你有用!!
【讨论】:
谢谢 :) 很有帮助以上是关于如何使用 swift 2.0 制作 http post json 请求参数的主要内容,如果未能解决你的问题,请参考以下文章
SpriteKit, Swift 2.0 - 在游戏地图上生成对象
使用 MKZoomScale 调整 MKAnnotationView 的大小 - Swift 2.0