我试图找到使用Alamofire从Swift 4调用ecobee的API的正确语法。
I'm trying to find the correct syntax for calling ecobee's API from Swift 4 using Alamofire.
他们的cURL示例:
curl -H "Content-Type: text/json" -H "Authorization: Bearer ACCESS_TOKEN" 'api.ecobee/1/thermostat?format=json&body=\{"selection":\{"selectionType":"registered","selectionMatch":"","includeRuntime":true\}\}'我最接近解决方案的是这个
The closest I've been to a solution is this
func doRequest() { guard let url = URL(string: "api.ecobee/1/thermostat?format=json") else { return } let parameters: Parameters = [ "selection": [ "selectionType": "registered", "selectionMatch": "" ] ] let headers: HTTPHeaders = [ "Content-Type": "text/json", "Authorization": "Bearer \(core.accessToken)" ] let req = AF.request(url, method: .get, parameters: parameters, encoding: JSONEncoding.default, headers: headers) .responseJSON { response in print("Error:", response.error?.localizedDescription ?? "no error") print("Data:", String(data: response.data!, encoding: .utf8)!) } debugPrint(req) }运行此命令时,呼叫最终失败,状态码为408,服务器超时
When I run this, the call ultimately fails with status code 408, a server timeout.
当我将HTTP方法更改为使用.post时,调用完成,但响应为内部状态3,消息为由于通信错误,更新失败。
When I change the HTTP method to use .post, the call completes, but the response is an internal status 3 with message "Update failed due to a communication error."
有人能帮我弄清楚我在做错什么,然后再浪费第二天试图破解它吗?
Can anyone help me figure out what I'm doing wrong before I waste another day trying to hack my way through it?
推荐答案Ecobee的请求格式有些奇怪,因为它使用了表单编码的参数,但是其中一个值是JSON编码的主体。您需要做一些准备工作,因为Alamofire并不自然支持这种功能。这只是示例代码,您需要做一些工作以使其更安全。
Ecobee's request format is a bit bizarre, as it uses form encoded parameters, but one of the values is a JSON encoded body. You'll have to do a little bit of prep work, as Alamofire doesn't naturally support something like this. This is just sample code, you'll need to do the work to make it safer.
首先,对JSON参数进行编码并获取 String 值:
First, encode the JSON parameters and get the String value:
let jsonParameters = ["selection": ["selectionType": "registered", "selectionMatch": ""]] let jsonData = try! JSONEncoder().encode(jsonParameters) let jsonString = String(decoding: jsonData, as: UTF8.self)然后,创建实际的参数和标头值:
Then, create the actual parameters and headers values:
let parameters = ["format": "json", "body": jsonString] let token = "token" let headers: HTTPHeaders = [.authorization(bearerToken: token), .contentType("text/json")] let url = URL(string: "api.ecobee/1/thermostat")!并发出请求:
AF.request(url, parameters: parameters, headers: headers).responseJSON { response in ... }更多推荐
用于ecobee请求的Alamofire语法
发布评论