我正在快速使用URLSession通过php将帖子发送到我的Web服务,该php从$ _POST [“ varname”]获取数据。
我发现将var放入request.httpBody起作用,并将var放入上载data(with:from :)的数据中。
那么,这两种方式有什么区别?我该选哪一个?
php服务是PHP7,swift是version4。
httpBody样式示例:
private func read(){
let url = URL(string: "http://mywebservice.com/index.php")!
var request = URLRequest(url: url)
request.httpMethod = "POST"
let string = "username=user1&password=password1"
request.httpBody = string.data(using: .utf8)
let task = URLSession.shared.dataTask(with: request){ (data, response, error) in
//do with data from server
}
task.resume()
}
数据样式示例:
private func read2(){
let url = URL(string: "http://mywebservice.com/index.php")!
var request = URLRequest(url: url)
request.httpMethod = "POST"
let string = "username=user1&password=password1"
let data = string.data(using: .utf8)!
let task = URLSession.shared.uploadTask(with: request, from: data){ (data, response, error) in
//do with data from server
}
task.resume()
}