URLRequest获取HTTP错误502和“通过对等方重置连接”

时间:2016-07-08 19:35:47

标签: swift3

使用此代码时出现以下错误:

        if let url = URL(string: "<valid web service url string>") {
        var request = URLRequest(url: url)
        request.httpMethod = "GET"
        request.setValue("Basic \(base64Authorization)", forHTTPHeaderField: "Authorization")

        let task = URLSession.shared.dataTask(with: request, completionHandler: {(data, response, error) in
            if error == nil {

相同的代码在Xcode 7.3中没有返回错误,但在转换为Swift 3后Xcode 8中出现错误。

1 个答案:

答案 0 :(得分:0)

这是因为Swift 3提案SE-0054

base64Authorization以这种方式声明:

    static var base64Authorization:String! {
    get {
        if base64Auth == nil {
            let keyString = "<my key string>"
            let plainTextData = keyString.data(using: .utf8, allowLossyConversion: false) as Data!
            base64Auth = plainTextData!.base64EncodedString(options: .endLineWithLineFeed) as String!
        }

        return base64Auth
    }
}

base64Authorization返回一个Optional,它搞砸了“Basic \(base64Authorization)”HTTP设置。

这个base64Authorization声明解决了这个问题:

    static var base64Authorization:String {
    get {
        if base64Auth == nil {
            let keyString = "<my key string>"
            let plainTextData = keyString.data(using: .utf8, allowLossyConversion: false) as Data!
            base64Auth = plainTextData!.base64EncodedString(options: .endLineWithLineFeed) as String
        }

        return base64Auth!
    }
}