JSON NSURLRequest with credentials

2019-07-20 12:30发布

I have an api in my swift app that needs some extra authorization. There are some examples provided by the service but none in swift.

My Code:

    let request = NSURLRequest(URL: NSURL(string: "https://www.kimonolabs.com/api/au4sl00w?apikey=iFotcJDm95fB6Ua7XiZRDZA0jl3uYWev")!)

Example in Pyhton

import urllib2
request = urllib2.Request("https://www.kimonolabs.com/api/au4sl00w? apikey=iFotcJDm95fB6Ua7XiZRDZA0jl3uYWev", headers={"authorization" : "Bearer    A5ve02gq40itf0eoYfT5ny6drZwcysxx"})
contents = urllib2.urlopen(request).read()

Example in Ruby

require 'rest_client'
response = RestClient.get('https://www.kimonolabs.com/api/au4sl00w?apikey=iFotcJDm95fB6Ua7XiZRDZA0jl3uYWev', {'authorization' => 'Bearer A5ve02gq40itf0eoYfT5ny6drZwcysxx'});
print(response);

Example in R

library('RCurl')
library('rjson')
json <- getURL('https://www.kimonolabs.com/api/au4sl00w?apikey=iFotcJDm95fB6Ua7XiZRDZA0jl3uYWuc',
  httpheader = c(authorization='Bearer A5ve02gq40itf0eoYfT5ny6drZwcysxx'))
obj <- fromJSON(json)
print(obj)

So, how can I do this in Swift?

1条回答
聊天终结者
2楼-- · 2019-07-20 13:09

Modified answer from: "How to make an HTTP request + basic auth in Swift".

I believe it would look something like this (and assuming your API_ID is au4sl00w) :

let token = "yourToken"

// create the request
let url = NSURL(string: "https://www.kimonolabs.com/api/au4sl00w?apikey=iFotcJDm95fB6Ua7XiZRDZA0jl3uYWev")
let request = NSMutableURLRequest(URL: url)
request.HTTPMethod = "GET"
request.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization")

And be sure to create a new access token, now that this one is public :)

查看更多
登录 后发表回答