Making an HTTP request with a header in Swift

I am trying to make an Imgur API HTTP request. I am trying to get all the images associated with the "cat" tag. URL according to the Imgur API: https://api.imgur.com/3/gallery/t/cats

The Imgur API states the following authorization required to receive receive requests:

For publicly accessible, public and anonymous resources, such as obtaining info images, viewing 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 want to anonymously upload images (no image
linked to an account), or if you want to create an anonymous
album. This allows us to find out which application is accessing the API.

 Authorization: Client-ID YOUR_CLIENT_ID 

I reviewed the following questions and tried the things suggested there, but none of them helped.

JSON NSURLRequest with credentials

Quick GET request with parameters

How to make Http-get and install httpHeader in Swift?

My current code is:

 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 constantly get a status code 403, that is, authorization is required. What am I doing wrong?

+6
source share
1 answer

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

 request.setValue("Client-ID <your_client_id>", forHTTPHeaderField: "Authorization") 
+12
source

All Articles