// 这个session可以使用刚才创建的。
let session = URLSession(configuration: .default)
// 设置URL
let url = "http://127.0.0.1/api/"
var request = URLRequest(url: URL(string: url)!)
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
request.httpMethod = "POST"
// 设置要post的内容,字典格式
let postData = ["email":"user@xxx.com","password":"123456"]
let postString = postData.compactMap({ (key, value) -> String in
return "\(key)=\(value)"
}).joined(separator: "&")
request.httpBody = postString.data(using: .utf8)
// 后面不解释了,和GET的注释一样
let task = session.dataTask(with: request) {(data, response, error) in
do {
let r = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.mutableContainers) as! NSDictionary
print(r)
} catch {
print("无法连接到服务器")
return
}
}
task.resume()