Php HTTP Post参数通过json编码传递给$\u Post

Php HTTP Post参数通过json编码传递给$\u Post,php,json,post,swift3,Php,Json,Post,Swift3,我不知道如何正确发送POST参数 我的Swift 3: let parameters = ["name": "thom", "password": "12345"] as Dictionary<String, String> let url = URL(string: "https://mywebsite.com/test.php")! let session = URLSession.shared var request = URLRequest(url: url) request

我不知道如何正确发送POST参数

我的Swift 3:

let parameters = ["name": "thom", "password": "12345"] as Dictionary<String, String>
let url = URL(string: "https://mywebsite.com/test.php")!
let session = URLSession.shared
var request = URLRequest(url: url)
request.httpMethod = "POST"
do
{
    request.httpBody = try JSONSerialization.data(withJSONObject: parameters)
}
catch let error
{
    print(error.localizedDescription)
}
request.addValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
let task = session.dataTask(with: request as URLRequest, completionHandler: 
{
    data, response, error in
    guard error == nil else
    {
        print(error as Any)
        return
    }           
    guard let data = data else
    {
        return
    }
    do 
    {
        if let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [String: Any] 
        {
            print(json)
            print(json["post"]!)
        }
        else
        {
            print("no json")
        }
    }
    catch let error
    {
        print(error.localizedDescription)
    }
})
task.resume()
如果我将其设置为
application/x-www-form-urlencoded
,我会得到:

["post": empty]
empty
["{\"name\":\"thom\",\"password\":\"12345\"}": , "post": not_empty]
not_empty

如何将字典作为$POST键/值对而不是json编码的字符串发送到服务器?

您希望将请求转义成
x-www-form-urlencoded
请求,如下所示:

let parameters = ["name": "thom", "password": "12345"]
let url = URL(string: "https://mywebsite.com/test.php")!

var request = URLRequest(url: url)
request.httpMethod = "POST"
request.updateHttpBody(with: parameters)
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")

let task = session.dataTask(with: request) { data, response, error in
    guard let data = data, error == nil else {
        print("\(error)")
        return
    }

    // handle response here
}
task.resume()
在哪里


这对你来说可能很有趣,很有趣,但不确定它有什么帮助。我需要将参数字典作为键/值对传递给我的$\u POST变量。如果我没有在客户端对我的参数进行json_编码,我会得到一个错误,说我不能将type AnyObject传递给type Data?我已经看到了那个线程。这就是我获得swift代码的地方(来自零票的答案)。我不想向服务器传递查询字符串。我想传递字典。一旦你有了
key=value
字符串数组,然后使用
joined(分隔符:“&”)
将它们组合在一起。这看起来很棒。如何/在何处添加这些扩展名?现在,只需将它们放在进行网络工作的
.swift
文件中(但不是放在现有的
/
结构定义中,而是放在之前或之后)。从长远来看,您可能会将它们放在单独的
.swift
文件中。谢谢。我将它们放在一个新文件中:extensions.swift工作正常。
let parameters = ["name": "thom", "password": "12345"]
let url = URL(string: "https://mywebsite.com/test.php")!

var request = URLRequest(url: url)
request.httpMethod = "POST"
request.updateHttpBody(with: parameters)
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")

let task = session.dataTask(with: request) { data, response, error in
    guard let data = data, error == nil else {
        print("\(error)")
        return
    }

    // handle response here
}
task.resume()
extension URLRequest {

    /// Populate the `httpBody` of `application/x-www-form-urlencoded` request.
    ///
    /// - parameter parameters:   A dictionary of keys and values to be added to the request

    mutating func updateHttpBody(with parameters: [String : String]) {
        let parameterArray = parameters.map { (key, value) -> String in
            return "\(key.addingPercentEncodingForQueryValue()!)=\(value.addingPercentEncodingForQueryValue()!)"
        }
        httpBody = parameterArray.joined(separator: "&").data(using: .utf8)
    }
}

extension String {

    /// Percent escape value to be added to a HTTP request
    ///
    /// This percent-escapes all characters besides the alphanumeric character set and "-", ".", "_", and "*".
    /// This will also replace spaces with the "+" character as outlined in the application/x-www-form-urlencoded spec:
    ///
    /// http://www.w3.org/TR/html5/forms.html#application/x-www-form-urlencoded-encoding-algorithm
    ///
    /// - returns: Return percent escaped string.

    func addingPercentEncodingForQueryValue() -> String? {
        let generalDelimitersToEncode = ":#[]@?/"
        let subDelimitersToEncode = "!$&'()*+,;="

        var allowed = CharacterSet.urlQueryAllowed
        allowed.remove(charactersIn: "\(generalDelimitersToEncode)\(subDelimitersToEncode)")

        return addingPercentEncoding(withAllowedCharacters: allowed)?.replacingOccurrences(of: " ", with: "+")
    }
}