Swift2 如何使用swift 2.0生成http post json请求参数

Swift2 如何使用swift 2.0生成http post json请求参数,swift2,Swift2,我需要使用swift2.0中的nsurl会话将json请求参数发送到服务器。我不知道如何创建json请求参数 让jsonObj=[“用户名”:“管理员”,“密码”:“123”,“设备ID”:“87878”] 但是它没有ping到方法体,因此我得到了失败响应请尝试下面的代码 let parameters = ["Username":"Admin", "Password":"123","DeviceId":"87878"] as Dictionary<String, String>

我需要使用swift2.0中的nsurl会话将json请求参数发送到服务器。我不知道如何创建json请求参数

让jsonObj=[“用户名”:“管理员”,“密码”:“123”,“设备ID”:“87878”]

但是它没有ping到方法体,因此我得到了失败响应

请尝试下面的代码

    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()
让参数=[“用户名”:“管理员”,“密码”:“123”,“设备ID”:“87878”]作为字典
let request=NSMutableURLRequest(URL:NSURL(string:YOURURL)!)
let session=NSURLSession.sharedSession()
request.HTTPMethod=“POST”
//注意:添加相应的“内容类型”和“接受”标题。在本例中,我使用了application/json。
request.addValue(“应用程序/json”,forHTTPHeaderField:“内容类型”)
request.addValue(“application/json”,forHTTPHeaderField:“Accept”)
request.HTTPBody=试试看!NSJSONSerialization.dataWithJSONObject(参数、选项:[])
让task=session.dataTaskWithRequest(请求){数据,响应,错误
防护数据!=无其他{
打印(“未找到数据:\(错误)”)
返回
}
做{
如果让json=尝试NSJSONSerialization.JSONObjectWithData(data!,选项:[])作为NSDictionary{
打印(“响应:\(json)”)
}否则{
让jsonStr=NSString(data:data!,encoding:NSUTF8StringEncoding)//不抛出错误,但不抛出NSDictionary
打印(“错误无法解析JSON:\(jsonStr)”)
}
}捕获let解析错误{
print(parseError)//记录`JSONObjectWithData'引发的错误`
让jsonStr=NSString(数据:data!,编码:NSUTF8StringEncoding)
打印(“错误无法分析JSON:'\(jsonStr)'”)
}
}
task.resume()
希望它对你有用

试试下面的代码

    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()
让参数=[“用户名”:“管理员”,“密码”:“123”,“设备ID”:“87878”]作为字典
let request=NSMutableURLRequest(URL:NSURL(string:YOURURL)!)
let session=NSURLSession.sharedSession()
request.HTTPMethod=“POST”
//注意:添加相应的“内容类型”和“接受”标题。在本例中,我使用了application/json。
request.addValue(“应用程序/json”,forHTTPHeaderField:“内容类型”)
request.addValue(“application/json”,forHTTPHeaderField:“Accept”)
request.HTTPBody=试试看!NSJSONSerialization.dataWithJSONObject(参数、选项:[])
让task=session.dataTaskWithRequest(请求){数据,响应,错误
防护数据!=无其他{
打印(“未找到数据:\(错误)”)
返回
}
做{
如果让json=尝试NSJSONSerialization.JSONObjectWithData(data!,选项:[])作为NSDictionary{
打印(“响应:\(json)”)
}否则{
让jsonStr=NSString(data:data!,encoding:NSUTF8StringEncoding)//不抛出错误,但不抛出NSDictionary
打印(“错误无法解析JSON:\(jsonStr)”)
}
}捕获let解析错误{
print(parseError)//记录`JSONObjectWithData'引发的错误`
让jsonStr=NSString(数据:data!,编码:NSUTF8StringEncoding)
打印(“错误无法分析JSON:'\(jsonStr)'”)
}
}
task.resume()
希望它对你有用

谢谢,这很有帮助