• Mac之swift中系统原生请求方法的使用


    import Cocoa

    class ViewController: NSViewController {

        override var representedObject: Any? {

            didSet {

            // Update the view, if already loaded.

            }

        }

        //6断点续传

        var downTask: URLSessionDownloadTask?

        var resumeData: Data?

        @IBAction func startDown(_ sender: NSButton) {

            let defaultConfigObject = URLSessionConfiguration.default

            let session = URLSession(configuration: defaultConfigObject, delegate: self, delegateQueue: OperationQueue.main)

            let url = URL(string: "http://")

            let task = session.downloadTask(with: url!)

            self.downTask = task

            task.resume()

        }

        

        @IBAction func stopDown(_ sender: NSButton) {

            self.downTask?.cancel(byProducingResumeData: { (data) in

                self.resumeData = data

            })

        }

        @IBAction func resumeDown(_ sender: NSButton) {

            let defaultConfigObject = URLSessionConfiguration.default

            let session = URLSession(configuration: defaultConfigObject, delegate: self, delegateQueue: OperationQueue.main)

            self.downTask = session.downloadTask(withResumeData: self.resumeData!)

            self.downTask?.resume()

        }

        override func viewDidLoad() {

            super.viewDidLoad()

            

            //Cookie编程

            //添加Cookie

            let cookie = HTTPCookie(properties: [HTTPCookiePropertyKey.domain : ".reddit.com",HTTPCookiePropertyKey.path : "/"])

            HTTPCookieStorage.shared.setCookie(cookie!)

            //删除Cookie

            if let cookies = HTTPCookieStorage.shared.cookies {

                for cookie in cookies {

                    HTTPCookieStorage.shared.deleteCookie(cookie)

                }

            }

            

            

        }

        ////1 使用系统默认的方式创建URLSession 基本流程如下

        let kServerBaseUrl = "http://127.0.0.1/iosxHelper/SAPI"

        func urlSessionNoDelegateTest() {

            //创建一个默认的Session配置

            let defaultConfigObject = URLSessionConfiguration.default

            //创建URLSession,对于系统的默认的代理进行收到数据处理的情况,设置delegate参数

            //为nil,同时设置代理执行的队列为主线程队列,在此也可以创建自己的私有队列

            let session = URLSession(configuration: defaultConfigObject, delegate: nil, delegateQueue: OperationQueue.main)

            let url = URL(string: kServerBaseUrl + "/VersionCheck")!

            //构造URLRequest对象, (接口的url路径,缓存规则协议约定的策略,超时时间)

            var request = URLRequest(url: url, cachePolicy: .useProtocolCachePolicy, timeoutInterval: 30)

            request.httpMethod = "POST"

            request.setValue("application/x-www-form-urlencode", forHTTPHeaderField: "content-type")

            let post = "versionNo=1.0&platform=Mac&channel=appstore*appName=DBAppx"

            let postData = post.data(using: String.Encoding.utf8)

            request.httpBody = postData

            let dataTask = session.dataTask(with: request) { (data, response, error) -> Void in

                let responseStr = String(data: data!, encoding: String.Encoding.utf8)

                print("data = (String(describing: responseStr))")

            }

            dataTask.resume()

        }

        //2使用自定义代理方法创建URLSession

        func urlSessionDelegateTest() {

            //使用默认配置

            let defaultConfigObject = URLSessionConfiguration.default

            //创建session并设置代理

            let session = URLSession(configuration: defaultConfigObject, delegate: self, delegateQueue: OperationQueue.main)

            let url = URL(string: kServerBaseUrl + "/Version")!

            var request = URLRequest(url: url, cachePolicy: .useProtocolCachePolicy, timeoutInterval: 30)

            request.httpMethod = "POST"

            request.setValue("application/x-www-form-urlencode", forHTTPHeaderField: "content-type")

            let post = "versionNo=1.0&platform=Mac&channel=appstore*appName=DBAppx"

            let postData = post.data(using: String.Encoding.utf8)

            let uploadTask = session.uploadTask(with: request, from: postData) { (data, response, error) -> Void in

                let responseStr = String(data: data!, encoding: String.Encoding.utf8)

                print("uploadTask data = (String(describing: responseStr))")

            }

            uploadTask.resume()

        }

        //3文件下载

        func urlSessionDownLoadFileTest() {

            let defaultConfigObject = URLSessionConfiguration.default

            //创建session制定代理和任务队列

            let session = URLSession(configuration: defaultConfigObject, delegate: self, delegateQueue: OperationQueue.main)

            //制定下载文件的URL

            let url = URL(string: "http://...png")

            //创建Download任务

            let task = session.downloadTask(with: url!)

            task.resume()

        }

        //4文件上传 流式文件上传客户端代码

        func urlSeseionUploadFileTst() {

            let uploadURL = URL(string: "http://127.0.0.1/fileUpload.php")!

            var request = URLRequest(url: uploadURL)

            request.httpMethod = "POST"

            //要上传的路径,假设document目录下有个AppBkIcon.png文件

            let uploadFileURL = URL(fileURLWithPath: NSHomeDirectory()).appendingPathComponent("Documents").appendingPathComponent("ppBkIcon.png")

            request.setValue("applicaiton/octet-stream", forHTTPHeaderField: "Content-type")

            let defaultConfigObject = URLSessionConfiguration.default

            let session = URLSession(configuration: defaultConfigObject, delegate: self, delegateQueue: OperationQueue.main)

            let uploadTask = session.uploadTask(with: request, fromFile: uploadFileURL) { (data, reponse, error) -> Void in

                if error != nil {

                    print("error (String(describing: error))")

                }

            }

            uploadTask.resume()

        }

        //5表单文件上传

        func urlSessionUploadFormFileTest() {

            //服务器地址

            let urlString = "http:127.0.0.1/formUpload.php"

            let url = URL(string: urlString)

            //上传文件的路径

            let fileURL = URL(fileURLWithPath: NSHomeDirectory()).appendingPathComponent("Documents").appendingPathComponent("AppBkIcon.png")

            let fileName = fileURL.lastPathComponent

            let fileData = try? Data(contentsOf: fileURL)

            let boundary = "-bounday"

            //上传的数据缓存

            var dataSend = Data()

            //bounary参数填充开始

            dataSend.append("--(boundary) ".data(using: String.Encoding.utf8)!)

            //form表单的参数

            dataSend.append("Content-Disposition: form-data; name="file";filename="(fileName)" ".data(using: String.Encoding.utf8)!)

            dataSend.append("Content-Type: applicaiton/octet-stream ".data(using: String.Encoding.utf8)!)

            dataSend.append(fileData!)

            dataSend.append(" ".data(using: String.Encoding.utf8)!)

            //boundary参数填充结束

            dataSend.append("--(boundary)-- ".data(using: String.Encoding.utf8)!)

            //请求参数

            var request = URLRequest(url: url!)

            request.httpMethod = "POST"

            request.httpBody = dataSend

            request.setValue("multipart/form-data; boundary=(boundary)", forHTTPHeaderField: "Content-Type")

            

            let sessionConfiguration = URLSessionConfiguration.default

            let session = URLSession(configuration: sessionConfiguration, delegate: self, delegateQueue: nil)

            

            //发起上传任务

            let sessionUploadTask = session.uploadTask(with: request, from: dataSend)

            sessionUploadTask.resume()

        }

        

        //服务器端php上传处理代码,脚本文件formUpload.php

        //    <?php

        //    if ($_FILES["file"]["error"] > 0)

        //    {

        //    echo "Return Code: ".$_FILES["file"]["error"]."<br />";

        //    }

        //    else

        //    {

        //        echo "Upload: ".$_FILE["file"]["name"]."<br />"

        //        echo "Type: ".$_FILE["file"]["type"]."<br />"

        //        echo "Size: ".$_FILE["file"]["size"] / 1024."kb<br />"

        //        echo "Temp file: ".$_FILE["file"]["tmp_name"]."<br />"

        //        if (file_exists("upload/". $_FILES["file"]["name"]))

        //        {

        //            echo $_FILES["file"]["name"]. "already exists.";

        //        }

        //        else

        //        {

        //            move_upload_file($_FILES["file"]["name"], "upload/". $_FILES["file"]["name"]);

        //            echo "Stroed in: ". "upload/". _FILES["file"]["name"];

        //        }

        //    }

        //    ?>

        //新建一个formUpload.html文件

        //    <html>

        //        <body>

        //            <form aciton="fileUpload.php" method="psot" enctype"multipart/form-data">

        //            <label for="file">FileName:</label>

        //            <input type="file" name="file" id="file" />

        //            <br />

        //            <input type="submit" name="submit" value="Submit" />

        //        </body>

        //    </html>

        //将上述formUpload.php和fromUpload.html都复制到XAMPP的htdocs跟目录,完成服务端发布然后客户端测试

        

        

        //缓存策略

        /****

         *1.userProtocolCachePolicy:协议规定的缓存策略 模式使用这种策略

         *2.reloadIgnoringLocalCacheData: 不适用缓存,永远适用网路数据

         *3.returnCacheDataElseLoad: 适用缓存数据,不管数据是否过期,如果缓存没有数据才请求网络数据

         *4.returnCacheDataDontLoad: 仅仅适用缓存数据

         **/

        

        

        //7 使用实例

        let kServerBaseUrl1 = "http://www.iosxhelper.com/"

        func httpGetTest() {

            let httpClient = HTTPClient()

            let urlString = "(kServerBaseUrl1)("/VersionCheck")"

            let url = URL(string: urlString)

            httpClient.get(url!, parameters: nil, success: { (responseObject: Any?) -> Void in

                print("get data (responseObject!)")

            }) { (error: Error?) -> Void in

                

            }

        }

        func postStringTest() {

            let httpClient = HTTPClient()

            let urlString = "(kServerBaseUrl1)(/VersionCheck)"

            let url = URL(string: urlString)

            let paras = "versionNo=1.0&platform=Mac&channel=appstore&appName=DBAppX"

            httpClient.post(url!, parameters: paras, success: { (responseObject: Any?) -> Void in

                print("post String responseObject = (responseObject)")

            }) { (error: Error?) -> Void in

                

            }

        }

        func postDictionaryTest() {

            let httpClient = HTTPClient()

            let urlString = "(kServerBaseUrl1)("/VersionCheck")"

            let url = URL(string: urlString)

            let paras = ["verisonNo":"1.0","platform":"Mac","channel":"appstore","appName":"DBAppX"]

            httpClient.post(url!, parameters: paras, success: { (responseObject: Any?) -> Void in

                print("post Dictonary responseObject =(responseObject!)")

            }) { (error: Error?) -> Void in

                

            }

        }

    }

  • 相关阅读:
    JS_判断浏览器.
    JQ_使用AJAX获取SINA股票代码
    Struts2中的OGNL详解
    CSS原理与CSS经验分享
    Struts 与 Velocity 的集成
    30条HTML代码编写指南 for入门者
    OGNL使用小结
    Visual C++ 6.0 插件系列介绍
    C语言编译过程总结详解
    Web.xml配置详解
  • 原文地址:https://www.cnblogs.com/sundaymac/p/10638728.html
Copyright © 2020-2023  润新知