一、介绍

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同步和异步请求的更多相关文章

  1. ASIHTTPRequest系列(一):同步和异步请求

    ASIHTTPRequest系列(一):同步和异步请求 发表于8个月前(2013-11-27 19:21)   阅读(431) | 评论(0) 6人收藏此文章, 我要收藏 赞0 ASIHTTPRequ ...

  2. C# ASP.NET Core使用HttpClient的同步和异步请求

    引用 Newtonsoft.Json // Post请求 public string PostResponse(string url,string postData,out string status ...

  3. $.post 和 $.get 设置同步和异步请求

    由于$.post() 和 $.get() 默认是 异步请求,如果需要同步请求,则可以进行如下使用:在$.post()前把ajax设置为同步:$.ajaxSettings.async = false;在 ...

  4. ASIHTTP 框架,同步、 异步请求、 上传 、 下载

    ASIHTTPRequest详解 ASIHTTPRequest 是一款极其强劲的 HTTP 访问开源项目.让简单的 API 完成复杂的功能,如:异步请求,队列请求,GZIP 压缩,缓存,断点续传,进度 ...

  5. 《C# 爬虫 破境之道》:第一境 爬虫原理 — 第四节:同步与异步请求方式

    前两节,我们对WebRequest和WebResponse这两个类做了介绍,但两者还相对独立.本节,我们来说说如何将两者结合起来,方式有哪些,有什么不同. 1.4.1 说结合,无非就是我们如何发送一个 ...

  6. js中同步与异步请求方式

    异步请求方式: $.ajax({ url : 'your url', data:{name:value}, cache : false, async : true, type : "POST ...

  7. Jquery的同步和异步请求

    1 异步请求:    1.1 $.ajax       $.ajax({                url : 'your url',                data:{name:valu ...

  8. ASP.NET Core使用HttpClient的同步和异步请求

    using System; using System.Collections.Generic; using System.Collections.Specialized; using System.I ...

  9. NSURLConnection和NSMutableURLRequest 实现同步、异步请求

    我是走向ios的一个小书童,我有很多不懂的,新鲜的知识去学习,去掌握! 我首先要吐槽一下: 那些不负责的博友!你分享知识本来是好事!可是你直接Control+V就是你的不对了! 尼玛,直接Contro ...

随机推荐

  1. 005.KVM日常管理2-virt管理

    一 安装管理工具 [root@kvm-host ~]# rpm -qa|grep libguestfs-tools #查看相关管理工具,若没安装,可使用yum安装.   二 日常管理 2.1 命令格式 ...

  2. 004.Autofs自动挂载

    一 安装autofs [root@imxhy data]# yum -y install autofs 二 编辑自动挂载相关配置 2.1 修改master [root@imxhy ~]# vi /et ...

  3. 使用Django简单编写一个XSS平台

    1) 简要描述        原理十分简单2333,代码呆萌,大牛勿喷 >_< 2) 基础知识 XSS攻击基本原理和利用方法 Django框架的使用 3) Let's start 0x01 ...

  4. linux学习笔记-6.权限

    1.创建a.txt和b.txt文件,将他们设为其拥有者和所在组可写入,但其他以外的人则不可写入 chmod ug+w,o-w a.txt b.txt 2.创建c.txt文件所有人都可以写和执行 chm ...

  5. Redis介绍及部署在CentOS7上(一)

    0.Redis目录结构 1)Redis介绍及部署在CentOS7上(一) 2)Redis指令与数据结构(二) 3)Redis客户端连接以及持久化数据(三) 4)Redis高可用之主从复制实践(四) 5 ...

  6. linux 驱动之LCD驱动(有framebuffer)

    <简介> LCD驱动里有个很重要的概念叫帧缓冲(framebuffer),它是Linux系统为显示设备提供的一个接口,应用程序在图形模式允许对显示缓冲区进行读写操作.用户根本不用关心物理显 ...

  7. 【BZOJ 4819】 4819: [Sdoi2017]新生舞会 (0-1分数规划、二分+KM)

    4819: [Sdoi2017]新生舞会 Time Limit: 10 Sec  Memory Limit: 128 MBSubmit: 601  Solved: 313 Description 学校 ...

  8. KVM源代码阅读--内核版本3.17.4

    为了更加深入的学习虚拟化,因此我必须把KVM源代码搞清楚,这是一个必须要挖的坑.我会把自己的一些阅读的代码贴上来,可能会有理解不对的地方,希望和大家一起交流,请多提意见,以便于纠正错误.所用的内核版本 ...

  9. 使用CefSharp在.Net程序中嵌入Chrome浏览器(十)——独立文件夹部署

    CefSharp本身携带了一大堆文件,这些文件默认直接释放在exe文件底下,这种方式本身没有什么问题,但多了一大堆文件后不是很好看.本文这里就介绍一个方法,使得可以将CEF相关的文件部署到独立的文件夹 ...

  10. 利用dynamic简化数据库的访问

    今天写了一个数据库的帮助类,代码如下. public static class DbEx { public static dynamic ReadToObject(this IDataReader r ...