我正在尝试向Imgur API发出HTTP请求。我正在尝试检索与标签相关的所有图像"猫。"根据Imgur API,网址为:https://api.imgur.com/3/gallery/t/cats
Imgur API声明了以下有关获取请求所需的授权:
用于公共只读和匿名资源,例如获取图像 信息,查找用户评论等,你需要做的就是发送一个 您的请求中包含
client_id
的授权标头。这也是 如果您想匿名上传图片(没有图片的话),则可以使用 被绑定到一个帐户),或者如果你想创建一个匿名的 专辑。这让我们知道哪个应用程序正在访问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的状态代码,这意味着需要授权。我做错了什么?
答案 0 :(得分:21)
我认为您需要将 Client-ID 字符串添加到您的实际客户端ID中,如标头值所示:
request.setValue("Client-ID <your_client_id>", forHTTPHeaderField: "Authorization")
答案 1 :(得分:2)
已更新为快速4:
func fetchPhotoRequest(YOUR_CLIENT_ID: String) {
let string = "https://photoslibrary.googleapis.com/v1/albums"
let url = NSURL(string: string)
let request = NSMutableURLRequest(url: url! as URL)
request.setValue(YOUR_CLIENT_ID, forHTTPHeaderField: "Authorization") //**
request.httpMethod = "GET"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
let session = URLSession.shared
let mData = session.dataTask(with: request as URLRequest) { (data, response, error) -> Void in
if let res = response as? HTTPURLResponse {
print("res: \(String(describing: res))")
print("Response: \(String(describing: response))")
}else{
print("Error: \(String(describing: error))")
}
}
mData.resume()
}