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 ...
随机推荐
- 学习linux-基础-操作系统结构
操作系统结构图 物理层: CPU:( Central Processing Unit)是一块超大规模的集成电路,是一台计算机的运算核心(Core)和控制核心( Control Unit).它的功能主要 ...
- 重写(Override) 重载(Overload)
重写(Override) 重写是子类对父类的允许访问的方法的实现过程进行重新编写, 返回值和形参都不能改变.即外壳不变,核心重写! 重载(Overload)- 参数必须不同 重载(overloadin ...
- 分类器评估方法:精确度-召回率-F度量(precision-recall-F_measures)
注:本文是人工智能研究网的学习笔记 Precision和Recall都能够从下面的TP,TN,FP,FN里面计算出来. 几个缩写的含义: 缩写 含义 P condition positive N co ...
- linux 下安装 RZ SZ命令 以及使用
对于经常使用Linux系统的人员来说,少不了将本地的文件上传到服务器或者从服务器上下载文件到本地,rz / sz命令很方便的帮我们实现了这个功能,rz是把win的文件上传到linux上 sz是吧 ...
- nginx File not found 错误(转)
当我没初始配在lnmp的时候,用浏览器打开查看php能否解析网页的时出现File not found 不用惊奇让我我们分析一下 使用php-fpm解析PHP,"No input file s ...
- TVS二极管和稳压二极管的区别
TVS二极管和稳压二极管的区别 TVS管超过它的耐压值后,会瞬间导通短路,反应速度在ns级, 而稳压管是稳压作用的,超过它的稳压值,只要功率不超过它的耐受值,就会稳定在它的稳压值范围内. TVS是瞬态 ...
- ARM Memory Copy
MODULE ARM_MEMORY PUBLIC ARM_MEMCPY PUBLIC ARM_MEMSET PUBLIC ARM_MEMSET8 PUBLIC ARM_MEMSET16 PUBLIC ...
- Ubuntu 14 安装Java(JRE、JDK)、Maven
JRE vs OpenJDK vs Oracle JDK JRE(Java Runtime Environment),它是你运行一个基于Java语言应用程序的所正常需要的环境.如果你不是一个程序员的话 ...
- Cygwin、MinGw、mingw-w64,MSys msys2区别与联系
https://www.biaodianfu.com/cygwin-ming-msys.html http://www.mingw-w64.org/doku.php http://blog.csdn. ...
- Revit API批量布置函数doc.Create.NewFamilyInstances();
start ] ;); if (xyzStart.X > pb.Max.X || xyzStart.Y < pb.Max.Y) ...