【发布时间】:2021-08-02 19:47:20
【问题描述】:
如何用 swift 调用这个 php post 请求?
我学习了很多教程,但都没有用。
我目前的尝试看起来像这样,但它不起作用:
let request = NSMutableURLRequest(url: NSURL(string: "https://example.com/lovetanks/setGabriel.php")! as URL)
request.httpMethod = "POST"
let postString = "kiss=\(kiss)&cuddle=\(cuddle)&talk=\(talk)&chat=\(chat)"
request.httpBody = postString.data(using: .utf8)
let task = URLSession.shared.dataTask(with: request as URLRequest) {
data, response, error in
if error != nil {
print("error=\(String(describing: error))")
return
}
}
task.resume()
当我使用浏览器执行此操作时,我会输入:
https://example.com/lovetanks/setName.php?kiss=2&cuddle=1&talk=3.5&chat=7.876
你们有什么想法吗?
【问题讨论】:
-
什么不起作用?您是否收到错误、不正确的数据等?
-
响应和错误说明了什么?
-
如果你用浏览器打开它并在那里得到结果,它很可能是一个 GET 请求,而不是一个 POST。
-
完全不相关(也不是问题的根源),而不是
let request = NSMutableURLRequest(url: NSURL(string: "https://example.com/lovetanks/setGabriel.php")! as URL),而是var request = URLRequest(url: URL(string: "https://example.com/lovetanks/setGabriel.php")!)。不要使用那些NS类,而是直接使用 Swift 类型。