Swift3.0:Get/Post同步和异步请求
Posted 程序猿
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Swift3.0:Get/Post同步和异步请求相关的知识,希望对你有一定的参考价值。
一、介绍
Get和Post区别:
- Get是从服务器上获取数据,Post是向服务器发送数据。
- 对于Get方式,服务端用Request.QueryString获取变量的值,对于Post方式,服务端用Request.From获取提交的数据。
- Get是把参数数据队列加到提交表单的ACTION属性所指的URL中,值和表单内的各个字段一一对应。
- Post是通过HTTP Post机制,将表单内各个字段和其内容放置在html HEADER内一起传送到ACTION属性所指的URL地址。用户看不到这个过程。
- Get安全性非常低,Post安全性较高;但是Get方式的执行效率比Post方法好。
- Get方式的安全性较Post方式差些,若包含机密信息,则建议用Post数据提交方式。
- 在数据查询时,建议用Get方式;在做数据添加、删除、修改时,建议用Post方式。
缓存策略:
public enum CachePolicy : UInt { case useProtocolCachePolicy //基础策略 case reloadIgnoringLocalCacheData //忽略本地存储 case reloadIgnoringLocalAndRemoteCacheData // 忽略本地和远程存储,总是从原地址下载 case returnCacheDataElseLoad //首先使用缓存,如果没有就从原地址下载 case returnCacheDataDontLoad //使用本地缓存,从不下载,如果没有本地缓存,则请求失败,此策略多用于离线操作 case reloadRevalidatingCacheData // 若本地缓存是有效的则不下载,其他任何情况总是从原地址下载 }
二、示例
Get同步请求:
//MARK: - 同步Get方式 func synchronousGet(){ // 1、创建URL对象; let url:URL! = URL(string:"http://api.3g.ifeng.com/clientShortNews?type=beauty"); // 2、创建Request对象 // url: 请求路径 // cachePolicy: 缓存协议 // timeoutInterval: 网络请求超时时间(单位:秒) let urlRequest:URLRequest = URLRequest(url: url, cachePolicy: .useProtocolCachePolicy, timeoutInterval: 10) // 3、响应对象 var response:URLResponse? // 4、发出请求 do { let received = try NSURLConnection.sendSynchronousRequest(urlRequest, returning: &response) let dic = try JSONSerialization.jsonObject(with: received, options: JSONSerialization.ReadingOptions.allowFragments) print(dic) //let jsonStr = String(data: received, encoding:String.Encoding.utf8); //print(jsonStr) } catch let error{ print(error.localizedDescription); } }
Get异步请求:
//在控制器定义全局的可变data,用户存储接收的数据 var jsonData:NSMutableData = NSMutableData()
//MARK: - 异步Get方式 func asynchronousGet(){ // 1、创建URL对象; let url:URL! = URL(string:"http://api.3g.ifeng.com/clientShortNews?type=beauty"); // 2、创建Request对象 // url: 请求路径 // cachePolicy: 缓存协议 // timeoutInterval: 网络请求超时时间(单位:秒) let urlRequest:URLRequest = URLRequest(url: url, cachePolicy: .useProtocolCachePolicy, timeoutInterval: 10) // 3、连接服务器 let connection:NSURLConnection? = NSURLConnection(request: urlRequest, delegate: self) connection?.schedule(in: .current, forMode: .defaultRunLoopMode) connection?.start() }
// MARK - NSURLConnectionDataDelegate extension GetPostViewController:NSURLConnectionDataDelegate{ func connection(_ connection: NSURLConnection, didReceive response: URLResponse) { //接收响应 } func connection(_ connection: NSURLConnection, didReceive data: Data) { //收到数据 self.jsonData.append(data); } func connectionDidFinishLoading(_ connection: NSURLConnection) { //请求结束 //let jsonStr = String(data: self.jsonData as Data, encoding:String.Encoding.utf8); //print(jsonStr) do { let dic = try JSONSerialization.jsonObject(with: self.jsonData as Data, options: JSONSerialization.ReadingOptions.allowFragments) print(dic) } catch let error{ print(error.localizedDescription); } } }
Post同步请求:
//MARK: - 同步Post方式 func synchronousPost() { // 1、创建URL对象; let url:URL! = URL(string:"http://api.3g.ifeng.com/clientShortNews"); // 2、创建Request对象 // url: 请求路径 // cachePolicy: 缓存协议 // timeoutInterval: 网络请求超时时间(单位:秒) var urlRequest:URLRequest = URLRequest(url: url, cachePolicy: .useProtocolCachePolicy, timeoutInterval: 10) // 3、设置请求方式为POST,默认是GET urlRequest.httpMethod = "POST" // 4、设置参数 let str:String = "type=beauty" let data:Data = str.data(using: .utf8, allowLossyConversion: true)! urlRequest.httpBody = data; // 5、响应对象 var response:URLResponse? // 6、发出请求 do { let received = try NSURLConnection.sendSynchronousRequest(urlRequest, returning: &response) let dic = try JSONSerialization.jsonObject(with: received, options: JSONSerialization.ReadingOptions.allowFragments) print(dic) //let jsonStr = String(data: received, encoding:String.Encoding.utf8); //print(jsonStr) } catch let error{ print(error.localizedDescription); } }
Post异步请求:
//在控制器定义全局的可变data,用户存储接收的数据 var jsonData:NSMutableData = NSMutableData()
//MARK: - 异步Post方式 func asynchronousPost(){ // 1、创建URL对象; let url:URL! = URL(string:"http://api.3g.ifeng.com/clientShortNews"); // 2、创建Request对象 // url: 请求路径 // cachePolicy: 缓存协议 // timeoutInterval: 网络请求超时时间(单位:秒) var urlRequest:URLRequest = URLRequest(url: url, cachePolicy: .useProtocolCachePolicy, timeoutInterval: 10) // 3、设置请求方式为POST,默认是GET urlRequest.httpMethod = "POST" // 4、设置参数 let str:String = "type=beauty" let data:Data = str.data(using: .utf8, allowLossyConversion: true)! urlRequest.httpBody = data; // 5、连接服务器 let connection:NSURLConnection? = NSURLConnection(request: urlRequest, delegate: self) connection?.schedule(in: .current, forMode: .defaultRunLoopMode) connection?.start() }
// MARK - NSURLConnectionDataDelegate extension GetPostViewController:NSURLConnectionDataDelegate{ func connection(_ connection: NSURLConnection, didReceive response: URLResponse) { //接收响应 } func connection(_ connection: NSURLConnection, didReceive data: Data) { //收到数据 self.jsonData.append(data); } func connectionDidFinishLoading(_ connection: NSURLConnection) { //请求结束 //let jsonStr = String(data: self.jsonData as Data, encoding:String.Encoding.utf8); //print(jsonStr) do { let dic = try JSONSerialization.jsonObject(with: self.jsonData as Data, options: JSONSerialization.ReadingOptions.allowFragments) print(dic) } catch let error{ print(error.localizedDescription); } } }
三、解析结果
{ body = ( { cThumbnail = "http://d.ifengimg.com/w166_h120/p2.ifengimg.com/ifengiclient/ipic/2017040117/swoole_location_8b6bbc5951ce5734d8f4a623f594f4ee_4245440126_size203_w1000_h1500.jpg"; cid = 1; comments = 0; commentsUrl = "http://share.iclient.ifeng.com/news/sharenews.f?&fromType=spider&aid=301341"; commentsall = 0; content = ""; ctime = "2017-04-01 17:30:01"; id = "shortNews_301341"; img = ( { size = { height = 720; width = 480; }; url = "http://d.ifengimg.com/mw480/p2.ifengimg.com/ifengiclient/ipic/2017040117/swoole_location_8b6bbc5951ce5734d8f4a623f594f4ee_4245440126_size203_w1000_h1500.jpg"; } ); likes = 86; link = { type = shortNews; url = "http://api.iclient.ifeng.com/clientShortNewsDetail?id=301341"; }; praise = 9284; shareTitle = "\U51e4\U51f0\U65b0\U95fb\U7f8e\U5973\U56fe\U7247"; shareUrl = "http://share.iclient.ifeng.com/news/sharenews.f?&fromType=spider&aid=301341"; source = ""; staticImg = ""; status = 1; thumbnail = "http://d.ifengimg.com/w166/p2.ifengimg.com/ifengiclient/ipic/2017040117/swoole_location_8b6bbc5951ce5734d8f4a623f594f4ee_4245440126_size203_w1000_h1500.jpg"; title = "\U51e4\U51f0\U65b0\U95fb\U7f8e\U5973\U56fe\U7247"; tread = 738; type = shortNews; utime = "2017-04-01 17:30:01"; }, { .............. .............. .............. }
四、完整代码
// // GetPostViewController.swift // NetWorkTest // // Created by 夏远全 on 2017/4/3. // Copyright ? 2017年 夏远全. All rights reserved. // import UIKit class GetPostViewController: UIViewController { //在控制器定义全局的可变data,用户存储接收的数据 var jsonData:NSMutableData = NSMutableData() override func viewDidLoad() { super.viewDidLoad() } //========================================Get==========================================// //MARK: - 同步Get方式 func synchronousGet(){ // 1、创建URL对象; let url:URL! = URL(string:"http://api.3g.ifeng.com/clientShortNews?type=beauty"); // 2、创建Request对象 // url: 请求路径 // cachePolicy: 缓存协议 // timeoutInterval: 网络请求超时时间(单位:秒) let urlRequest:URLRequest = URLRequest(url: url, cachePolicy: .useProtocolCachePolicy, timeoutInterval: 10) // 3、响应对象 var response:URLResponse? // 4、发出请求 do { let received = try NSURLConnection.sendSynchronousRequest(urlRequest, returning: &response) let dic = try JSONSerialization.jsonObject(with: received, options: JSONSerialization.ReadingOptions.allowFragments) print(dic) //let jsonStr = String(data: received, encoding:String.Encoding.utf8); //print(jsonStr) } catch let error{ print(error.localizedDescription); } } //MARK: - 异步Get方式 func asynchronousGet(){ // 1、创建URL对象; let url:URL! = URL(string:"http://api.3g.ifeng.com/clientShortNews?type=beauty"); // 2、创建Request对象 // url: 请求路径 // cachePolicy: 缓存协议 // timeoutInterval: 网络请求超时时间(单位:秒) let urlRequest:URLRequest = URLRequest(url: url, cachePolicy: .useProtocolCachePolicy, timeoutInterval: 10) // 3、连接服务器 let connection:NSURLConnection? = NSURLConnection(request: urlRequest, delegate: self) connection?.schedule(in: .current, forMode: .defaultRunLoopMode) connection?.start() } //========================================Post==========================================// //MARK: - 同步Post方式 func synchronousPost() { // 1、创建URL对象; let url:URL! = URL(string:"http://api.3g.ifeng.com/clientShortNews"); // 2、创建Request对象 // url: 请求路径 // cachePolicy: 缓存协议 // timeoutInterval: 网络请求超时时间(单位:秒) var urlRequest:URLRequest = URLRequest(url: url, cachePolicy: .useProtocolCachePolicy, timeoutInterval: 10) // 3、设置请求方式为POST,默认是GET urlRequest.httpMethod = "POST" // 4、设置参数 let str:String = "type=beauty" let data:Data = str.data(using: .utf8, allowLossyConversion: true)! urlRequest.httpBody = data; // 5、响应对象 var response:URLResponse? // 6、发出请求 do { let received = try NSURLConnection.sendSynchronousRequest(urlRequest, returning: &response) let dic = try JSONSerialization.jsonObject(with: received, options: JSONSerialization.ReadingOptions.allowFragments) print(dic) //let jsonStr = String(data: received, encoding:String.Encoding.utf8); //print(jsonStr) } catch let error{ print(error.localizedDescription); } } //MARK: - 异步Post方式 func asynchronousPost(){ // 1、创建URL对象; let url:URL! = URL(string:"http://api.3g.ifeng.com/clientShortNews"); // 2、创建Request对象 // url: 请求路径 // cachePolicy: 缓存协议 // timeoutInterval: 网络请求超时时间(单位:秒) var urlRequest:URLRequest = URLRequest(url: url, cachePolicy: .useProtocolCachePolicy, timeoutInterval: 10) // 3、设置请求方式为POST,默认是GET urlRequest.httpMethod = "POST" // 4、设置参数 let str:String = "type=beauty" let data:Data = str.data(using: .utf8, allowLossyConversion: true)! urlRequest.httpBody = data; // 3、连接服务器 let connection:NSURLConnection? = NSURLConnection(request: urlRequest, delegate: self) connection?.schedule(in: .current, forMode: .defaultRunLoopMode) connection?.start() } } // MARK - NSURLConnectionDataDelegate extension GetPostViewController:NSURLConnectionDataDelegate{ func connection(_ connection: NSURLConnection, didReceive response: URLResponse) { //接收响应 } func connection(_ connection: NSURLConnection, didReceive data: Data) { //收到数据 self.jsonData.append(data); } func connectionDidFinishLoading(_ connection: NSURLConnection) { //请求结束 //let jsonStr = String(data: self.jsonData as Data, encoding:String.Encoding.utf8); //print(jsonStr) do { let dic = try JSONSerialization.jsonObject(with: self.jsonData as Data, options: JSONSerialization.ReadingOptions.allowFragments) print(dic) } catch let error{ print(error.localizedDescription); } } }
以上是关于Swift3.0:Get/Post同步和异步请求的主要内容,如果未能解决你的问题,请参考以下文章
Okhttp 使用(同步、异步/get、post/上传文件)
FlutterHTTP 网络操作 ( 引入 http 插件 | 测试网站 | Get 请求 | Post 请求 | 将响应结果转为 Dart 对象 | Future 异步调用 )