【问题标题】:Call PHP Post with Swift 5使用 Swift 5 调用 PHP Post
【发布时间】: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 类型。

标签: swift http-post


【解决方案1】:

如果您想在浏览器中输入https://example.com/lovetanks/setName.php?kiss=2&cuddle=1&talk=3.5&chat=7.876,您可以发出GET 请求,如下所示:

var components = URLComponents(string: "https://example.com/lovetanks/setName.php")!
components.queryItems = [
    URLQueryItem(name: "kiss", value: "2"),
    URLQueryItem(name: "cuddle", value: "1"),
    URLQueryItem(name: "talk", value: "3.5"),
    URLQueryItem(name: "chat", value: "7.876")
]
components.percentEncodedQuery = components.percentEncodedQuery?.replacingOccurrences(of: "+", with: "%2B")

let task = URLSession.shared.dataTask(with: components.url!) { data, response, error in
    guard
        let responseData = data,
        let httpResponse = response as? HTTPURLResponse,
        200 ..< 300 ~= httpResponse.statusCode
    else {
        print("error=", String(describing: error), String(describing: response))
        return
    }

    // do something with `responseData` here
}
task.resume()

所以,请注意,因为这是一个 GET 请求,所以您根本不需要 URLRequest,因为您可以使用 URL。另请注意:

  • 我添加了一些基本错误处理(不仅检查基本网络错误,还检查非 2xx 状态代码的 HTTP 错误);

  • 我建议使用URLComponents(如https://stackoverflow.com/a/27724627/1271826 中所述),而不是手动构建URL。对于您的简单数值,URLComponents 不是绝对需要的,但随着您的 URL 变得更加复杂(例如,包括字符串值),使用 URLComponents 可以让您摆脱手动编码 URL 的麻烦。

  • 此外,您没有说明您是在 iOS 还是 macOS 中执行此操作。如果是后者,请记住转到目标设置的“签名和功能”部分并启用“应用沙盒”»“网络”»“传出连接(客户端)”。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-16
    • 1970-01-01
    • 2019-09-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多