Converting ecobee Alamofire request to use URLSession

随声附和 提交于 2019-12-25 03:29:18

问题


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

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