gpt4 book ai didi

swift - 将 ecobee Alamofire 请求转换为使用 URLSession

转载 作者:行者123 更新时间:2023-11-30 10:44:51 25 4
gpt4 key购买 nike

作为我上一个问题 ( Alamofire syntax for ecobee request ) 的后续问题,我更愿意仅使用 URLSession 来进行请求。

现在我使用以下代码返回超时且状态为 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()
}

关于swift - 将 ecobee Alamofire 请求转换为使用 URLSession,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55956309/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com