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

时间:2015-03-26 06:43:12

标签: json swift ssl

以下是我的登录功能。这是一个JSON POST请求,之前,当URL是http时,它运行得很完美。我附上了一个填充了用户名/密码的JSON。今天我们添加了一个SSL证书,在将URL切换到https后,它产生了这个错误:

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

我不确定发生了什么。我把这个错误输入谷歌并没有得到任何地方。我感谢任何帮助,谢谢!

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

1 个答案:

答案 0 :(得分:0)

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

NSObject, NSURLSessionDelegate, NSURLSessionTaskDelegate

在我的班级名称之后,然后添加这两个代表:

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

希望这有助于某人!