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

  

posted @ 2022-05-19 15:21  ziwuxian  阅读(239)  评论(0编辑  收藏  举报