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同步和异步请求的更多相关文章
- ASIHTTPRequest系列(一):同步和异步请求
ASIHTTPRequest系列(一):同步和异步请求 发表于8个月前(2013-11-27 19:21) 阅读(431) | 评论(0) 6人收藏此文章, 我要收藏 赞0 ASIHTTPRequ ...
- C# ASP.NET Core使用HttpClient的同步和异步请求
引用 Newtonsoft.Json // Post请求 public string PostResponse(string url,string postData,out string status ...
- $.post 和 $.get 设置同步和异步请求
由于$.post() 和 $.get() 默认是 异步请求,如果需要同步请求,则可以进行如下使用:在$.post()前把ajax设置为同步:$.ajaxSettings.async = false;在 ...
- ASIHTTP 框架,同步、 异步请求、 上传 、 下载
ASIHTTPRequest详解 ASIHTTPRequest 是一款极其强劲的 HTTP 访问开源项目.让简单的 API 完成复杂的功能,如:异步请求,队列请求,GZIP 压缩,缓存,断点续传,进度 ...
- 《C# 爬虫 破境之道》:第一境 爬虫原理 — 第四节:同步与异步请求方式
前两节,我们对WebRequest和WebResponse这两个类做了介绍,但两者还相对独立.本节,我们来说说如何将两者结合起来,方式有哪些,有什么不同. 1.4.1 说结合,无非就是我们如何发送一个 ...
- js中同步与异步请求方式
异步请求方式: $.ajax({ url : 'your url', data:{name:value}, cache : false, async : true, type : "POST ...
- Jquery的同步和异步请求
1 异步请求: 1.1 $.ajax $.ajax({ url : 'your url', data:{name:valu ...
- ASP.NET Core使用HttpClient的同步和异步请求
using System; using System.Collections.Generic; using System.Collections.Specialized; using System.I ...
- NSURLConnection和NSMutableURLRequest 实现同步、异步请求
我是走向ios的一个小书童,我有很多不懂的,新鲜的知识去学习,去掌握! 我首先要吐槽一下: 那些不负责的博友!你分享知识本来是好事!可是你直接Control+V就是你的不对了! 尼玛,直接Contro ...
随机推荐
- 利用HTML5定位功能,实现在百度地图上定位(转)
原文:利用HTML5定位功能,实现在百度地图上定位 代码如下: 测试浏览器:ie11定位成功率100%,Safari定位成功率97%,(add by zhj :在手机上测试(用微信内置浏览器打开),无 ...
- 006.Zabbix添加监控主机
一 配置步骤和流程 Zabbix完整的监控配置流程可以简单的描述为: Host groups(主机组)---->Hosts(主机)---->Applications(监控项组)----&g ...
- 如何对vue项目进行优化,加快首页加载速度
上个月上线了一个vue小项目,刚做完项目,打包上线之后,传到服务器上发现首页加载巨慢. 由于开发时间比较紧,我想着怎么快怎么来,因而在开发过程中没考虑过优化性能问题,酿成最后在带宽5M的情况下页面加载 ...
- db 文件 查看 打开 工具 db 中文 版 navicat 中文
韩梦飞沙 韩亚飞 313134555@qq.com yue31313 han_meng_fei_sha ======= db 中文 版 navicat 中文 ======= Navicatfo ...
- 【bfs】BZOJ1102- [POI2007]山峰和山谷Grz
最后刷个水,睡觉去.Bless All! [题目大意] 给定一个地图,为FGD想要旅行的区域,地图被分为n*n的网格,每个格子(i,j) 的高度w(i,j)是给定的.若两个格子有公共顶点,那么他们就是 ...
- BZOJ2832 : 宅男小C
首先将所有显然不在最优解中的外卖都删去,那么剩下的外卖价格越低,保质期也最短. 考虑三分订外卖的次数,然后贪心求解,每次尽量平均的时候可以做到最优化. 三分的时候,以存活天数为第一关键字,剩余钱数为第 ...
- ReentrantLock源码了解
1).ReentrantLock.tryLock //获取没有被其他线程持有的锁 //1).当没有被任何线程持有时,首先将计数器设置为1,并设置当前持有锁的线程为当前线程,最后返回true //2). ...
- QQ和微信一键加群加好友代码
QQ和微信一键加群加好友链接代码实现. 1.QQ加群加好友链接(借助腾讯QQ群推广链接和加好友链接实现) (1).加群技术链接: http://qun.qq.com/join.html (2).加好友 ...
- CentOS 7设置ulimit不生效的问题解决
sed -i 's/#UseLogin no/UseLogin yes/g' /etc/ssh/sshd_configservice sshd restart 重新登录后查看效果: ulimit -n ...
- 通过WinAPI播放PCM声音
在Windows平台上,播放PCM声音使用的API通常有如下两种. waveOut and waveIn:传统的音频MMEAPI,也是使用的最多的 xAudio2:C++/COM API,主要针对游戏 ...