ios - 在 Swift 中使用 header 发出 HTTP 请求

标签 ios swift nsurlsession imgur

我正在尝试向 Imgur API 发出 HTTP 请求。我正在尝试检索与标签“猫”关联的所有图像。根据 Imgur API 的 url 是:https://api.imgur.com/3/gallery/t/cats

Imgur API 对发出 get 请求所需的授权声明如下:

For public read-only and anonymous resources, such as getting image info, looking up user comments, etc. all you need to do is send an authorization header with your client_id in your requests. This also works if you'd like to upload images anonymously (without the image
being tied to an account), or if you'd like to create an anonymous
album. This lets us know which application is accessing the API.

Authorization: Client-ID YOUR_CLIENT_ID

我查看了以下问题并尝试了那里建议的事情,但没有一个有帮助。

JSON NSURLRequest with credentials

Swift GET request with parameters

How to make a Http get and set httpHeader in Swift?

我目前的代码是这样的:

let string = "https://api.imgur.com/3/gallery/t/cats"
let url = NSURL(string: string)
let request = NSMutableURLRequest(URL: url!)
request.setValue("clientIDhere", forHTTPHeaderField: "Authorization")
//request.addValue("clientIDhere", forHTTPHeaderField: "Authorization")
request.HTTPMethod = "GET"
let session = NSURLSession.sharedSession()

let tache = session.dataTaskWithRequest(request) { (data, response, error) -> Void in
    if let antwort = response as? NSHTTPURLResponse {
        let code = antwort.statusCode
        print(code)
    }
}
tache.resume()

但我不断收到 403 状态码,这意味着需要授权。我做错了什么?

最佳答案

我认为您需要将 Client-ID 字符串添加到您的实际客户端 ID 中作为 header 值:

request.setValue("Client-ID <your_client_id>", forHTTPHeaderField: "Authorization")

关于ios - 在 Swift 中使用 header 发出 HTTP 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34583840/

相关文章:

ios - 使用 iOS 社交框架为任何用户授权 session ?

ios - EZaudio在后台执行

ios - 接收器 ... 没有标识符错误的 segue

具有泛型参数的函数的 Swift 单元测试

ios - 如何为 NSURLSession 连接选择特定的网络接口(interface)?

Swift 4 - 如何在不重复代码的情况下调用从多个函数中的函数返回的一段代码?

ios - UIView 的 subview 或组件不随 View 移动

ios - 选择 UITabBarController 中的特定项目时,关于触发 "loading"UIView 有什么想法吗?

ios - 检查 bool 是否为真 x 秒 - Swift

ios - 有没有办法消除使用 [NSURLSessionConfiguration backgroundSessionConfiguration] 时的延迟?