我有这样的代码:
let request = NSMutableURLRequest(URL: NSURL(string: "http://myurl.com/webservice2/save_stamps.php")!)
request.HTTPMethod = "POST"
let postString = "facebook_id=x&pin=1234&count=1"
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)
request.setValue("keep-alive", forHTTPHeaderField: "Connection")
request.setValue("text/html", forHTTPHeaderField: "Content-Type")
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
data, response, error in
if error != nil {
println("error=\(error)")
return
}
println("response = \(response)")
let responseString = NSString(data: data, encoding: NSUTF8StringEncoding)
println("responseString = \(responseString)")
}
task.resume()
在xCode控制台中我可以看到:
response = <NSHTTPURLResponse: 0x7ff91950de90> { URL: http://myurl.com/webservice2/save_stamps.php } { status code: 200, headers {
Connection = "keep-alive";
"Content-Encoding" = gzip;
"Content-Length" = 20;
"Content-Type" = "text/html";
Date = "Fri, 07 Aug 2015 08:41:10 GMT";
Server = "Apache/2";
Vary = "Accept-Encoding";
} }
responseString = Optional()
我尝试使用&amp; count = 1更改count = 1,但没有任何变化。 问题在哪里?
也许有另一种方法可以简单地调用http而不获取任何数据?
答案 0 :(得分:0)
尝试此功能
func httpPost(url:String, postData: String, completion: String -> Void) {
var googleUrl = NSURL(string: url)
var request = NSMutableURLRequest(URL: googleUrl!)
request.HTTPMethod = "POST"
request.HTTPBody = postData.dataUsingEncoding(NSUTF8StringEncoding);
request.addValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
var session = NSURLSession.sharedSession()
let task = session.dataTaskWithRequest(request, completionHandler: { data, response, error in
completion(NSString(data: data, encoding: NSUTF8StringEncoding) as! String)
})
task.resume()
}
可以这样使用:
httpPost("http://myurl.com/webservice2/save_stamps.php", postData: "facebook_id=x&pin=1234&count=1") { result in
println(result)//result is your string-response from server
}