ios - URLSession 不会在 header swift 4 中传递 'Authorization' 键

标签 ios swift nsurlsession

我正在尝试在 URLRequest 的 header 中传递授权 key 。但是在服务器端没有收到 key 。从 postman 调用时相同的 API 工作正常。 header 中的任何其他 key 都可以正常工作,甚至授权 key 在服务器端也是可见的。

这是我的代码:

let headers = [
    "authorization": "token abcd"
]

var request = URLRequest.init(url: NSURL(string:
    "http://127.0.0.1:7000/api/channels?filter=contributed")! as URL)
request.httpMethod = "GET"
request.allHTTPHeaderFields = headers
let config = URLSessionConfiguration.default
config.httpAdditionalHeaders = headers
let session = URLSession.init(configuration: config)

let dataTask = session.dataTask(with: request, completionHandler: { (data, response, error) -> Void in
    if (error != nil) {
        print(error ?? "")
    } else {
        let httpResponse = response as? HTTPURLResponse
        print(httpResponse ?? "")
    }
})

如您所见,我尝试在 session 配置和请求中设置 token ,但均无效。

最佳答案

这似乎有效:

// Set the security header
private var credentials: String {
    return "\(participantId):\(password)"
}

private var basicAuthHeader: String {
    return "Basic \(credentials)"
}

func getSettings(participantId: Int, password: String) -> Bool {

    self.participantId = participantId
    self.password = password

    let path = "/settings/\(participantId)"
    guard let url = URL(string: "\(BASE_URL)\(path)") else {
        Log.e("Invalid URL string, could not convert to URL")
        return false
    }

    var urlRequest = URLRequest(url: url)
    urlRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")
    urlRequest.setValue(basicAuthHeader, forHTTPHeaderField: "Authorization")
    urlRequest.setValue(APP_FILE_NAME, forHTTPHeaderField: "User-Agent")

    // This is a synchronous wrapper extension around URLSession.dataTask()
    let (data, response, error) = URLSession.shared.synchronousDataTask(with: urlRequest)
    // Process the result...
}

注:我同事写的代码。谢谢约翰!

关于ios - URLSession 不会在 header swift 4 中传递 'Authorization' 键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46852680/

相关文章:

ios - 无法加载单元测试的底层模块

iOS - 以国际格式和英语获取本地日期和时间

ios - removeFromSuperview() 并不总是有效

json - 快速 json null 检查

ios - 如何获取失败的 NSURLSessionDownloadTask 的下载数据?

objective-c - 使用 objective-c 的同步 NSURLSessionDataTask

ios - 如何关闭文本字段中的键盘

ios - 如何将从互联网下载的数据保存到内部设备?

swift - 如何使用日期或日历更改UITextView中的值?

ios - 检查发生了哪种 NSURLSessionTask