gpt4 book ai didi

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

转载 作者:IT王子 更新时间:2023-10-29 05:19:00 25 4
gpt4 key购买 nike

我正在尝试向 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com