gpt4 book ai didi

ios - 如何使用 NSURLSession 快速发送 HTTPS POST 请求

转载 作者:搜寻专家 更新时间:2023-10-31 19:35:00 27 4
gpt4 key购买 nike

我一直在使用 HTTP 进行开发。当使用 HTTP 连接到开发服务器时,下面的代码工作得很好。但是,当我将方案更改为 https 时,它不会向服务器发送成功的 https 帖子。

要从 HTTP POST 切换到 HTTPS POST,我还需要做什么?

class func loginRemote(successHandler:()->(), errorHandler:(String)->()) {

let user = User.sharedInstance

// this is where I've been changing the scheme to https
url = NSURL(String: "http://url.to/login.page")

let request = NSMutableURLRequest(URL: url)

let bodyData = "email=\(user.email)&password=\(user.password)"
request.HTTPBody = bodyData.dataUsingEncoding(NSUTF8StringEncoding);

request.HTTPMethod = "POST"

let session = NSURLSession.sharedSession()

// posting login request
let task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in
if let httpResponse = response as? NSHTTPURLResponse {
if httpResponse.statusCode == 200 {
// email+password were good

successHandler()

} else {
// email+password were bad
errorHandler("Status: \(httpResponse.statusCode) and Response: \(httpResponse)")
}
} else {
NSLog("Unwrapping NSHTTPResponse failed")
}
})

task.resume()
}

最佳答案

您将必须实现 NSURLSessionDelegate 方法之一,以便它接受 SSL 证书。

class YourClass: Superclass, NSURLSessionDelegate {

class func loginRemote(successHandler:()->(), errorHandler:(String)->()) {
// ...
let session = NSURLSession(configuration: NSURLSessionConfiguration.defaultSessionConfiguration(),
delegate: self,
delegateQueue: nil)
// ...
}

func URLSession(session: NSURLSession, task: NSURLSessionTask, didReceiveChallenge challenge: NSURLAuthenticationChallenge, completionHandler: (NSURLSessionAuthChallengeDisposition, NSURLCredential!) -> Void) {
if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust {
let credential = NSURLCredential(trust: challenge.protectionSpace.serverTrust)
completionHandler(NSURLSessionAuthChallengeDisposition.UseCredential, credential)
}
}

}

警告:这将盲目地接受您尝试的任何 SSL 证书/连接。这不是一种安全的做法,但它允许您使用 HTTPS 测试您的服务器。

更新:Swift 4+

class YourClass: Superclass, URLSessionDelegate {

class func loginRemote(successHandler: ()->(), errorHandler:(String)->()) {
// ...
let session = URLSession(configuration: .default, delegate: self, delegateQueue: nil)
// ...
}

func urlSession(_ session: URLSession, didReceiveChallenge challenge: URLAuthenticationChallenge, completionHandler: (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust {
if let trust = challenge.protectionSpace.serverTrust {
completionHandler(.useCredential, URLCredential(trust: trust))
}
}
}

}

关于ios - 如何使用 NSURLSession 快速发送 HTTPS POST 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30741046/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com