joey joey - 4 years ago 426
Swift Question

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?

Answer Source

I think you need to prepend Client-ID string to your actual client ID as for the header value:

request.setValue("Client-ID <your_client_id>", forHTTPHeaderField: "Authorization")
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download