我正在尝试转换以下curl请求,Swagger给了我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'
正确设置了网址和标头。我仍得到回复:401 - 未经授权。
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()
我错过了什么吗?
答案 0 :(得分:4)
出现问题的是,您创建了一个完美的请求,然后通过仅使用网址而不是请求执行dataTask
来跳过所有请求。这样HTTPHeaders
不会随请求一起发送,因此未经授权。
只需将任务创建行更改为:
let task = URLSession.shared.dataTask(with: req) { data, response, error in
...
}