问题
As a followup to my last question (Alamofire syntax for ecobee request), I would prefer to just use URLSession for the request.
Now I'm back to a request that times out with status 408 using the following code:
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()
I suspect I'm not adding the query parameters correctly.
回答1:
I found my own solution using 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()
}
来源:https://stackoverflow.com/questions/55956309/converting-ecobee-alamofire-request-to-use-urlsession