我无法向接受字符串的服务器发送快速的后请求。服务器不接受JSON数据。苹果库中有什么方法吗?我找不到任何东西。
或者你甚至可以告诉我如何编写这样的方法来帮助我?
let url = NSURL(string: "myUrl")
var session = NSURLSession.sharedSession()
let request = NSMutableURLRequest(URL: url)
request.HTTPMethod = "POST"
var params = "login_act:'myUsername'&login_pwd:'myPassword'"
var err: NSError?
request.HTTPBody = NSJSONReadingOptions.
// The following method call does not accept the params variable type, although I need to send a String
request.HTTPBody = NSJSONSerialization.dataWithJSONObject(params, options: nil, error: &err)
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
var task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in
println("Response: \(response)")
var strData = NSString(data: data, encoding: NSUTF8StringEncoding)
println("Body: \(strData)")
任何帮助表示赞赏!!!
答案 0 :(得分:3)
如果服务器不接受json,那么将标题Content-Type设置为application / json的目的是什么。您有两个选项可以将内容作为json发送,也可以将表单请求作为表单提交发送。我会告诉你两种可能的方法,
第一个是将表单参数发布到url,它不接受json而是接受url编码的表单参数。
let url = NSURL(string: "myUrl")
var session = NSURLSession.sharedSession()
let request = NSMutableURLRequest(URL: url)
request.HTTPMethod = "POST"
var params = "login_act=myUsername&login_pwd=myPassword"
request.HTTPBody = params.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)
var err: NSError?
request.addValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
var task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in
println("Response: \(response)")
var strData = NSString(data: data, encoding: NSUTF8StringEncoding)
println("Body: \(strData)")
})
其他方法,如果您的服务器接受json参数,那么该方法与您所使用的方法非常相似。
let url = NSURL(string: "myUrl")
var session = NSURLSession.sharedSession()
let request = NSMutableURLRequest(URL: url)
request.HTTPMethod = "POST"
var params = ["login_act":"myUsername", "login_pwd":"myPassword"]
var err: NSError?
// The following method call does not accept the params variable type, although I need to send a String
request.HTTPBody = NSJSONSerialization.dataWithJSONObject(params, options: nil, error: &err)
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
var task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in
println("Response: \(response)")
var strData = NSString(data: data, encoding: NSUTF8StringEncoding)
println("Body: \(strData)")
})
答案 1 :(得分:1)
使用Alamofire与Swift进行HTTP联网可能会更好。