我正在对Swift中的Web服务器进行简单的HTTP Post调用,并试图通过Dictionary传递几个参数,但服务器似乎没有收到它们,我在这里缺少什么?我可以在PHP,Perl等中做到这一点,但还没有想到在Swift中传递POST参数。感谢。
var ret: NSData
var responseStr: NSString
var urlString = server + page
var url:NSURL = NSURL(string: urlString)! // Creating URL
var request = NSMutableURLRequest(URL: url) // Creating Http Request
request.HTTPMethod = "POST"
// these params don't seem to be recognized
let params = [
"projectid": "1234", "userid": "somename", "password": "pw"
] as Dictionary<String, String>
var err: NSError?
let requestBody = NSJSONSerialization.dataWithJSONObject(params, options: nil, error: &err)
request.HTTPBody = requestBody
var response: AutoreleasingUnsafeMutablePointer<NSURLResponse?> = nil
var error: NSErrorPointer? = nil
答案 0 :(得分:0)
服务器端应用程序通常需要一个值为Content-Type
的{{1}}标头来识别JSON格式的请求正文。所以在发出请求之前添加它:
application/json
另一种解决方案是使用像Just这样的库。您的要求是:
request.addValue("application/json", forHTTPHeaderField:"Content-Type")