Making HTTP Request with header in Swift

I am trying to make an HTTP request to the Imgur API. I am trying to retrieve all images associated with the tag "cats." The url, according to the Imgur API is: https://api.imgur.com/3/gallery/t/cats

the Imgur API states the following about the authorization needed to make get requests:

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

I've looked at the following questions and tried things suggested there, but none of them have helped.

JSON NSURLRequest with credentials

Swift GET request with parameters

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

My current code is this:

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

But I continually get a status code of 403, meaning authorization is required. What am I doing wrong?


我认为你需要将Client-ID字符串作为标题值附加到你的实际客户端ID:

request.setValue("Client-ID <your_client_id>", forHTTPHeaderField: "Authorization")
链接地址: http://www.djcxy.com/p/81444.html

上一篇: Imgur API图像搜索不返回数据

下一篇: 在Swift中使用头进行HTTP请求