简体   繁体   English

向 Openhab2 和 Swift 发布 API 请求

[英]Posting API request to Openhab2 and Swift

I am trying to post a request to my Openhab system from a custom Swift iOS application I am developing however I can't seem to get a response.我正在尝试从我正在开发的自定义 Swift iOS 应用程序向我的 Openhab 系统发布请求,但我似乎无法得到响应。

I'm using the below but can't get the sensor to trigger.我正在使用以下但无法触发传感器。

AF.request("http://192.168.1.1:8080/rest/items/BinarySensor", method: .post, parameters: ["":"ON"], encoding: URLEncoding.httpBody, headers: ["Content-Type":"text/plain"])

Any help appreciated.任何帮助表示赞赏。

You need to change your encoding to JSONEncoding.default and your headers to application/json.您需要将编码更改为 JSONEncoding.default,将标头更改为 application/json。 Here is how your request would look like now这是您的请求现在的样子

AF.request("http://192.168.1.1:8080/rest/items/BinarySensor", method: .post, parameters: ["":"ON"], encoding: JSONEncoding.default, headers: ["Content-Type":"application/json"])

I've gone down a different path.我走了一条不同的路。 Not using Alamofire and just using the standard Swift networking.不使用 Alamofire,只使用标准的 Swift 网络。 Postman allows the creation of multiple different language code blocks for a particular request so using the request it generates. Postman 允许为特定请求创建多个不同语言的代码块,以便使用它生成的请求。

If anyone wants to know how to do it without Alamofire the answer is below.如果有人想知道如何在没有 Alamofire 的情况下做到这一点,答案如下。

import Foundation

var semaphore = DispatchSemaphore (value: 0)

let parameters = "OFF"
let postData = parameters.data(using: .utf8)

var request = URLRequest(url: URL(string:"http://192.168.x.x:8080/rest/items/BinarySensor")!,timeoutInterval: Double.infinity)
request.addValue("text/plain", forHTTPHeaderField: "Content-Type")

request.httpMethod = "POST"
request.httpBody = postData

let task = URLSession.shared.dataTask(with: request) { data, response, error in 
  guard let data = data else {
    return
  }
  semaphore.signal()
}

task.resume()
semaphore.wait()

I'm sure there is a better way but this way works.我相信有更好的方法,但这种方法有效。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM