Convert CURL to URLRequest

无人久伴 提交于 2021-02-04 19:46:06

问题


I’m trying to converting the the following curl request Swagger gives me to URLRequest:

curl -X GET --header 'Accept: application/json' 
--header 'Authorization: key ttn-account-v2.<app-key>'
 'https://<app-id>.data.thethingsnetwork.org/api/v2/query'

URL and Headers are set correctly. Still I get the response: 401 - Not authorized.

let key = "ttn-account-v2.<app-key>"

let url = URL(string: "https://<app-id>.data.thethingsnetwork.org/api/v2/query")

var request = URLRequest(url: url!)

request.httpMethod = "GET"
request.addValue("application/json", forHTTPHeaderField: "Accept")
request.addValue("key \(key)", forHTTPHeaderField: "Authorization")

let task = URLSession.shared.dataTask(with: url!) { data, response, error in
    guard error == nil else {
        print(error!)
        return
    }
    guard let data = data else {
        print("Data is empty")
        return
    }

    let json = try! JSONSerialization.jsonObject(with: data, options: [])
    print(json)
}
task.resume()

Am I missing something?


回答1:


What is going wrong is that you create a perfect request but then skip it all together by doing a dataTask with just the url and not the request. This way the HTTPHeaders aren't send with the request, thus it is not authorised. Just change the task creation line to this:

let task = URLSession.shared.dataTask(with: req) { data, response, error in 
    ...
}


来源:https://stackoverflow.com/questions/46779004/convert-curl-to-urlrequest

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!