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);
        }
    }
}

时间: 2024-08-04 18:26:05

Swift3.0:Get/Post同步和异步请求的相关文章

[IOS_HTTP]NSURLConnection同步与异步请求

今天看到<WIN32多线程程序设计>的同步控制时,才发现原来自己对同步和异步的概念很模糊,甚至混淆.于是GOOGLE了一下.下面都是高人们的见解,简单明了. 同步是指:发送方发出数据后,等接收方发回响应以后才发下一个数据包的通讯方式.  异步是指:发送方发出数据后,不等接收方发回响应,接着发送下个数据包的通讯方式. 举个不太恰当的例子,就像:  SendMessage(...)  TRACE0("just  like  send");   PostMessage(...) 

关于jquery同步和异步请求问题总结

关于jquery同步和异步请求问题总结 问题 这几天做项目的时候,写脚本遇到一个问题,就是jquery异步请求和同步请求执行顺序不按代码顺序执行而是最后执行导致添加数据报错,添加到空值,这怎么忍,于是我去查找jquery api,终于知道了原来jquery默认异步请求,防止数据卡死,终于让我找到了这货 async,当async: true 时,ajax请求是异步的.当async : true 时,就是同步的,但是我又有个问题,怎么设置,这个在哪设置,用$.ajax去写这个操作,不,不太麻烦了,到

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

引用 Newtonsoft.Json // Post请求 public string PostResponse(string url,string postData,out string statusCode) { string result = string.Empty; //设置Http的正文 HttpContent httpContent = new StringContent(postData); //设置Http的内容标头 httpContent.Headers.ContentType

jquery 同步和异步请求

1. $.ajax 同步和异步请求 1 $.ajax({ 2 type: "POST", 3 url: "some.php", 4 async : true, // true 异步,false 同步 5 // or data:{name:"John",locationi:"Boston"} 6 data: "name=John&location=Boston", 7 success: functio

【Java&amp;Android开源库代码剖析】のandroid-async-http(如何设计一个优雅的Android网络请求框架,同时支持同步和异步请求)开篇

在<[Java&Android开源库代码剖析]のandroid-smart-image-view>一文中我们提到了android-async-http这个开源库,本文正式开篇来详细介绍这个库的实现,同时结合源码探讨如何设计一个优雅的Android网络请求框架.做过一段时间Android开发的同学应该对这个库不陌生,因为它对Apache的HttpClient API的封装使得开发者可以简洁优雅的实现网络请求和响应,并且同时支持同步和异步请求. 网络请求框架一般至少需要具备如下几个组件:1

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

ASIHTTPRequest详解 ASIHTTPRequest 是一款极其强劲的 HTTP 访问开源项目.让简单的 API 完成复杂的功能,如:异步请求,队列请求,GZIP 压缩,缓存,断点续传,进度跟踪,上传文件,HTTP 认证.在新的版本中,还加入了 Objective-C 闭包 Block 的支持,让我们的代码加轻简灵活. 下面就举例说明它的 API 用法. 发起一个同步请求 同步意为着线程阻塞,在主线程中使用此方法会使应用Hang住而不响应任何用户事件.所以,在应用程序设计时,大多被用在

同步和异步请求

// //  ViewController.m //  UI-NO-18 // //  Created by Bruce on 15/8/13. //  Copyright (c) 2015年 Bruce. All rights reserved. // #import "ViewController.h" #import "InfoModel.h" @interface ViewController () @end @implementation ViewCont

js中同步与异步请求方式

异步请求方式: $.ajax({ url : 'your url', data:{name:value}, cache : false, async : true, type : "POST", dataType : 'json/xml/html', success : function (result){ do something.... } }); 同步请求方式: $.ajax({ url : 'your url', data:{name:value}, cache : false

同步、异步请求

IOS之同步请求.异步请求.GET请求.POST请求 1.同步请求可以从因特网请求数据,一旦发送同步请求,程序将停止用户交互,直至服务器返回数据完成,才可以进行下一步操作, 2.异步请求不会阻塞主线程,而会建立一个新的线程来操作,用户发出异步请求后,依然可以对UI进行操作,程序可以继续运行 3.GET请求,将参数直接写在访问路径上.操作简单,不过容易被外界看到,安全性不高,地址最多255字节: 4.POST请求,将参数放到body里面.POST请求操作相对复杂,需要将参数和地址分开,不过安全性高