2

我正在尝试将 Swagger 给我的以下 curl 请求转换为 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 和标头设置正确。我仍然收到回复: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()

我错过了什么吗?

4

1 回答 1

5

出了问题的是您创建了一个完美的请求,然后通过dataTask只使用 url 而不是请求来跳过它。这样HTTPHeaders就不会随请求一起发送,因此未获得授权。只需将任务创建行更改为:

let task = URLSession.shared.dataTask(with: req) { data, response, error in 
    ...
}
于 2017-10-16T21:06:58.993 回答