作为我最后一个问题的后续(ecobee请求的alamofire语法(,我更喜欢只针对请求。
现在,我又回到了使用以下代码的状态408的请求:
guard let url = URL(string: "https://api.ecobee.com/1/thermostat") else { return }
let jsonParameters = [ "selection": [ "selectionType": "registered", "selectionMatch": "" ] ]
let jsonData = try! JSONEncoder().encode(jsonParameters)
let jsonString = String(decoding: jsonData, as: UTF8.self)
let queryParameters = ["format": "json", "body": jsonString]
let headers: HTTPHeaders = [.authorization(bearerToken: AUTH_TOKEN), .contentType("text/json")]
var request = try! URLRequest(url: url, method: .get, headers: headers)
request.httpBody = try! JSONEncoder().encode(queryParameters)
URLSession.shared.dataTask(with: request) { (data, resp, err) in
debugPrint(String(data: data!, encoding: .utf8)!)
}.resume()
我怀疑我没有正确添加查询参数。
我使用urlcomponents
找到了自己的解决方案func testRequest() {
guard var url = URLComponents(string: "https://api.ecobee.com/1/thermostat") else { return }
let jsonParameters = [ "selection": [ "selectionType": "registered", "selectionMatch": "" ] ]
let jsonData = try! JSONEncoder().encode(jsonParameters)
let jsonString = String(decoding: jsonData, as: UTF8.self)
let queryParameters = ["format": "json", "body": jsonString]
url.queryItems = queryParameters.map { URLQueryItem(name: $0.key, value: $0.value) }
let headers = [
"Authorization": "Bearer (core.accessToken)",
"Content-Type": "application/x-www-form-urlencoded; charset=utf-8"
]
var request = URLRequest(url: url.url!)
request.httpMethod = "GET"
request.allHTTPHeaderFields = headers
URLSession.shared.dataTask(with: request) { (data, resp, err) in
debugPrint(String(data: data!, encoding: .utf8)!)
}.resume()
}