如何更改 JSON POST 请求以处理 HTTPS

How to change JSON POST request to handle HTTPS

下面是我的登录功能。这是一个 JSON POST 请求,之前,当 URL 是 http 时,它可以完美地工作。我附上了一个JSON,里面填满了用户的username/password。今天我们添加了一个 SSL 证书,在将 URL 切换到 https 后,它产生了这个错误:

NSURLConnection/CFURLConnection HTTP load failed (kCFStreamErrorDomainSSL, -9843)

我不太确定发生了什么。我在 google 中输入了该错误,但没有得到任何结果。感谢您的帮助,谢谢!

func login(params : Dictionary<String, String>, url : String, postCompleted : (succeeded: Bool, msg: String) -> ()) {
    var request = NSMutableURLRequest(URL: NSURL(string: url)!)
    var session = NSURLSession.sharedSession()
    request.HTTPMethod = "POST"

    var err: NSError?
    request.HTTPBody = NSJSONSerialization.dataWithJSONObject(params, options: nil, error: &err)
    request.addValue("application/json", forHTTPHeaderField: "Content-Type")
    request.addValue("application/json", forHTTPHeaderField: "Accept")

    var task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in
        if response != nil {
            if response.isKindOfClass(NSHTTPURLResponse) {
                httpResponse = response as NSHTTPURLResponse
                if let authorizationID = httpResponse.allHeaderFields["Authorization"] as String! {
                    Locksmith.saveData(["id":authorizationID], forUserAccount: currentUser, inService: "setUpAuthorizationId")
                }
                else {
                    println("Failed")
                }

            }
        }
        var err: NSError?
        var json = NSJSONSerialization.JSONObjectWithData(data, options: .MutableLeaves, error: &err) as? NSDictionary

        // Did the JSONObjectWithData constructor return an error? If so, log the error to the console
        if(err != nil) {
            println(err!.localizedDescription)
            let jsonStr = NSString(data: data, encoding: NSUTF8StringEncoding)
            println("Error could not parse JSON: '\(jsonStr!)'")
            postCompleted(succeeded: false, msg: "Error")
        }
        else {
            // The JSONObjectWithData constructor didn't return an error. But, we should still
            // check and make sure that json has a value using optional binding.
            if let parseJSON = json {
                // Okay, the parsedJSON is here, let's get the value for 'success' out of it
                if let status = parseJSON["status"] as? String {
                    if let extractData = parseJSON["data"] as? NSDictionary {
                        let extractUserId:Int = extractData["id"] as Int
                        userId = extractUserId
                    }
                    if status == "success" {
                        postCompleted(succeeded: true, msg: "Logged in.")
                    } else {
                        let failMessage = parseJSON["message"] as? String
                        postCompleted(succeeded: false, msg: failMessage!)
                    }
                }
                return
            }
            else {
                // Woa, okay the json object was nil, something went worng. Maybe the server isn't running?
                let jsonStr = NSString(data: data, encoding: NSUTF8StringEncoding)
                println("Error could not parse JSON: \(jsonStr)")
                postCompleted(succeeded: false, msg: "Error")
            }
        }
    })

    task.resume()
}

使用 This awesome article 我能够解决我的问题。我需要做的就是添加:

NSObject, NSURLSessionDelegate, NSURLSessionTaskDelegate

在我的 class 名字之后,然后添加这两个代表:

    func URLSession(session: NSURLSession,
    didReceiveChallenge challenge:
    NSURLAuthenticationChallenge,
    completionHandler:
    (NSURLSessionAuthChallengeDisposition,
    NSURLCredential!) -> Void) {
        completionHandler(
            NSURLSessionAuthChallengeDisposition.UseCredential,
            NSURLCredential(forTrust:
                challenge.protectionSpace.serverTrust))
}

func URLSession(session: NSURLSession, task: NSURLSessionTask, willPerformHTTPRedirection response: NSHTTPURLResponse, newRequest request: NSURLRequest, completionHandler: (NSURLRequest!) -> Void) {
    var newRequest : NSURLRequest? = request
    println(newRequest?.description);
    completionHandler(newRequest)
}

在那之后,在我的实际请求中,我只需要更改:

var session = NSURLSession.sharedSession()

至:

        var configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
        var session = NSURLSession(configuration: configuration, delegate: self, delegateQueue:NSOperationQueue.mainQueue())

希望这对某人有所帮助!!