在 Swift 中使用 header 发出 HTTP 请求

Making HTTP Request with header in Swift

我正在尝试向 Imgur API 发出 HTTP 请求。我正在尝试检索与标签 "cats." 关联的所有图像 url,根据 Imgur API 是: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

我查看了以下问题并尝试了其中的建议,但其中 none 有帮助。

Swift GET request with parameters

我目前的代码是这样的:

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")

更新 swift 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()
}