ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

SwiftUI使用URLSession发送https请求免证书验证

2022-05-19 15:34:34  阅读:33  来源: 互联网

标签:MyHttp completionHandler URLSession request SwiftUI https let data


1 自定义MyHttp类

class MyHttp: NSObject, URLSessionDelegate {
    // 使用URLSession请求数据
    func httpGet(request: URLRequest,  completionHandler: @escaping (Data?, URLResponse?, Error?) -> Void) {
        let configuration = URLSessionConfiguration.default
        let session = URLSession(configuration: configuration, delegate: self, delegateQueue:OperationQueue.main)
        let dataTask = session.dataTask(with: request, completionHandler: completionHandler)
         
        //使用resume方法启动任务
        dataTask.resume()
    }
    
    func urlSession(_ session:URLSession, didReceive challenge:URLAuthenticationChallenge, completionHandler:@escaping (URLSession.AuthChallengeDisposition,URLCredential?) -> Void) {

            guard challenge.protectionSpace.authenticationMethod == "NSURLAuthenticationMethodServerTrust"else {
                return
            }

            let credential = URLCredential.init(trust: challenge.protectionSpace.serverTrust!)
            completionHandler(.useCredential,credential)
      }
}

2. 调用MyHttp发送https请求

 

let myhttp = MyHttp()
var request = URLRequest(url: URL(string: "https://test.aaaa.cn/login")!)
request.httpMethod = "POST"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.allHTTPHeaderFields = ["User-Agent": "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;)","Referer":"https://test.aaaa.cn/"]
request.httpBody = "{\"user\":\"zhangsan\", \"pwd\":\"123456\"}".data(using: .utf8)
myhttp.httpGet(request: request, completionHandler: {(data, response, error) -> Void in
    if error != nil{
        print(error?.localizedDescription)
    }else{
        let str = String(data: data!, encoding: String.Encoding.utf8)
        print("访问成功,获取数据如下:")
        print(str)
    }
})

  

标签:MyHttp,completionHandler,URLSession,request,SwiftUI,https,let,data
来源: https://www.cnblogs.com/ziwuxian/p/16288673.html

专注分享技术,共同学习,共同进步。侵权联系[admin#icode9.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有