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

文章展示了如何创建一个名为MyHttp的类,该类使用URLSession进行HTTPSPOST请求。类中包含了处理服务器信任认证的方法,并提供了发送请求及处理响应数据的示例。在给定的代码片段中,请求了一个登录接口,并设置了请求头信息。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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)
      }
}
  1. 调用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)
    }
})`在这里插入代码片`
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值