廢話不多說,直接上代碼。
得到:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
// 创建一个会话,这个会话可以复用 let session = URLSession(configuration: .default) // 设置URL let url = "http://127.0.0.1/api/" var UrlRequest = URLRequest(url: URL(string: url)!) // 创建一个网络任务 let task = session.dataTask(with: UrlRequest) {(data, response, error) in do { // 返回的是一个json,将返回的json转成字典r let r = try JSONSerialization.jsonObject(with: data!, options: []) as! NSDictionary print(r) } catch { // 如果连接失败就... print("无法连接到服务器") return } } // 运行此任务 task.resume() |
POST:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
// 这个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() |
本文由 落格博客 原創撰寫:落格博客 » swift4 urlSession get和post網絡請求
轉載請保留出處和原文鏈接:https://www.logcg.com/archives/3120.html
膜拜 大神啊