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 ...
随机推荐
- mybatis generator修改默认生成的sql模板
相关连接: mybatis-generator扩展教程系列 -- 自定义sql xml文件 git项目地址
- 23.python中的类属性和实例属性
在上篇的时候,我们知道了:属性就是属于一个对象的数据或者函数,我们可以通过句点(.)来访问属性,同时 python 还支持在运作中添加和修改属性. 而数据变量,类似于: name = 'scolia' ...
- code vs 2602 最短路径问题
题目描述 Description 平面上有n个点(n<=100),每个点的坐标均在-10000~10000之间.其中的一些点之间有连线.若有连线,则表示可从一个点到达另一个点,即两点间有通路,通 ...
- BZOJ 3812主旋律
求一个图中强联通图的个数. 一看就是容斥啦,但这种二进制高端操作还是学习一下Candy?dalao 注释在代码里 好久没更了... #include<bits/stdc++.h> usin ...
- 【拓扑排序】BZOJ4010-[HNOI2015]菜肴制作
[题目大意] 是要求N个点的一个拓扑序,且满足以下条件:编号1的位置尽可能靠前,在满足所有限制,编号2的位置尽可能靠前,以此类推. [思路] 一开始觉得优先队列维护一下拓扑就好了.然而样例告诉我们是不 ...
- linux socket TCP UDP bind 同义IP和port
//TCP and UDP can bind to the same IP & port. #include <sys/types.h> #include <sys/sock ...
- delphi 结构体和TList的用法
type PRecord = ^TMyRec; TMyRec = record s: string[8]; i: integer; d: double;end;var MyL ...
- JasperReports+iReport在eclipse中的使用(转)
一.介绍 1)它可以PDF,HTML,XML等多种形式产生报表或动态报表,在新版本还支持CSV,XLS,RTF等格式的报表: 2)它按预定义的XML文档来组织数据,来源多(如:关系数据库,Java容器 ...
- Linux ftp 命令
一.ftp的get命令和mget命令有何不同? get一次只下载一个文件:mget一次可以下载多个文件,而且支持通配符,需要注意的是在mget的时侯,需要对每一个文件都选择y/n,如果想不交互的下载全 ...
- 【Centos】centos查看磁盘使用情况
1.查看分区和磁盘 lsblk 查看分区和磁盘 2.查看空间使用情况 df -h 查看空间使用情况 3.分区工具查看分区信息 fdisk -l 分区工具查看分区信息 4.查看分区 cfdisk /de ...