如何使用NSURLSession在swift中发送HTTPS POST请求

时间:2015-06-09 19:24:08

标签: ios swift nsurlsession

我一直在使用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()
}

1 个答案:

答案 0 :(得分:2)

您必须实施其中一种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))
            }
        }
    }

}