使用POST方法在Swift中进行HTTP请求

我正在尝试在Swift中运行HTTP请求" title="HTTP请求">HTTP请求,以将2个参数发布到URL。

例:

链接: www.thisismylink.com/postName.php

参数:

id = 13

name = Jack

最简单的方法是什么?

我什至不想阅读回复。我只想发送该文件,以通过PHP文件对数据库进行更改。

回答:

在Swift 3及更高版本中,您可以:

let url = URL(string: "http://www.thisismylink.com/postName.php")!

var request = URLRequest(url: url)

request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")

request.httpMethod = "POST"

let parameters: [String: Any] = [

"id": 13,

"name": "Jack & Jill"

]

request.httpBody = parameters.percentEncoded()

let task = URLSession.shared.dataTask(with: request) { data, response, error in

guard let data = data,

let response = response as? HTTPURLResponse,

error == nil else { // check for fundamental networking error

print("error", error ?? "Unknown error")

return

}

guard (200 ... 299) ~= response.statusCode else { // check for http errors

print("statusCode should be 2xx, but is \(response.statusCode)")

print("response = \(response)")

return

}

let responseString = String(data: data, encoding: .utf8)

print("responseString = \(responseString)")

}

task.resume()

哪里:

extension Dictionary {

func percentEncoded() -> Data? {

return map { key, value in

let escapedKey = "\(key)".addingPercentEncoding(withAllowedCharacters: .urlQueryValueAllowed) ?? ""

let escapedValue = "\(value)".addingPercentEncoding(withAllowedCharacters: .urlQueryValueAllowed) ?? ""

return escapedKey + "=" + escapedValue

}

.joined(separator: "&")

.data(using: .utf8)

}

}

extension CharacterSet {

static let urlQueryValueAllowed: CharacterSet = {

let generalDelimitersToEncode = ":#[]@" // does not include "?" or "/" due to RFC 3986 - Section 3.4

let subDelimitersToEncode = "!$&'()*+,;="

var allowed = CharacterSet.urlQueryAllowed

allowed.remove(charactersIn: "\(generalDelimitersToEncode)\(subDelimitersToEncode)")

return allowed

}()

}

这将检查基本的网络错误以及高级HTTP错误。这也可以正确地对查询的参数进行转义。

请注意,我使用的nameof Jack & Jill来说明的正确x-www-form-

urlencoded结果name=Jack%20%26%20Jill,该结果是“百分比编码”的(即,空格替换为%20&值中的替换为%26)。

以上是 使用POST方法在Swift中进行HTTP请求 的全部内容, 来源链接: utcz.com/qa/428090.html

回到顶部