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

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

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

  

免责声明:本网信息来自于互联网,目的在于传递更多信息,并不代表本网赞同其观点。其原创性以及文中陈述文字和内容未经本站证实,对本文以及其中全部或者部分内容、文字的真实性、完整性、及时性本站不作任何保证或承诺,并请自行核实相关内容。本站不承担此类作品侵权行为的直接责任及连带责任。如若本网有任何内容侵犯您的权益,请及时联系我们,本站将会在24小时内处理完毕。
相关文章
返回顶部