我被下面的代码卡住了。如何在post方法中设置参数?
let params:[String:Any] = [
"email" : usr,
"userPwd" : pwdCode]
let url = NSURL(string:"http://inspect.dev.cbre.eu/SyncServices/api/jobmanagement/PlusContactAuthentication")
let request = NSMutableURLRequest(URL: url!)
request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
request.HTTPBody = params<what should do for Json parameter>
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
data, response, error in
if let httpResponse = response as? NSHTTPURLResponse {
if httpResponse.statusCode != 200 {
println("response was not 200: \(response)")
return
}
}
if error {
println("error submitting request: \(error)")
return
}
// handle the data of the successful response here
}
task.resume()发布于 2014-11-22 17:02:30
如果我没理解错这个问题
var configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
var session = NSURLSession(configuration: configuration)
var usr = "dsdd"
var pwdCode = "dsds"
let params:[String: AnyObject] = [
"email" : usr,
"userPwd" : pwdCode ]
let url = NSURL(string:"http://localhost:8300")
let request = NSMutableURLRequest(URL: url!)
request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
request.HTTPMethod = "POST"
var err: NSError?
request.HTTPBody = NSJSONSerialization.dataWithJSONObject(params, options: NSJSONWritingOptions.allZeros, error: &err)
let task = session.dataTaskWithRequest(request) {
data, response, error in
if let httpResponse = response as? NSHTTPURLResponse {
if httpResponse.statusCode != 200 {
println("response was not 200: \(response)")
return
}
}
if (error != nil) {
println("error submitting request: \(error)")
return
}
// handle the data of the successful response here
var result = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.allZeros, error: nil) as? NSDictionary
println(result)
}
task.resume()我建议使用AFNetworking。例如,请参阅Posting JSON data using AFNetworking 2.0。
发布于 2016-08-09 15:50:14
这就是如何设置参数和发送POST请求,使用Alamofire的简单方法。
让URL = NSURL(string:"https://SOME_URL/web.send.json")!let mutableURLRequest = NSMutableURLRequest(URL: URL) mutableURLRequest.HTTPMethod = "POST“let参数= ["api_key":"______","email_details":"fromname":"______"," subject”:“这是测试邮件主题”,"from":"support@apple.com","content":“嗨,这是一封测试邮件。”,“NSJSONSerialization.dataWithJSONObject(parameters,”:"_________"] do { mutableURLRequest.HTTPBody =尝试收件人选项:NSJSONWritingOptions()} mutableURLRequest.setValue("application/json",{ // No-op }_________forHTTPHeaderField:"Content-Type") Alamofire.request(mutableURLRequest) .responseJSON {打印响应(response.request) //原始URL请求打印(response.response) // URL响应打印(response.data) //服务器数据打印(response.result) //如果让JSON = response.result.value { print("JSON:(JSON)“)} }
https://stackoverflow.com/questions/27036233
复制相似问题