【发布时间】:2016-12-11 22:41:57
【问题描述】:
我不知道如何正确发送 POST 参数。
我的斯威夫特 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()
我的 PHP:
<?php
header('Content-Type: application/json');
if(empty($_POST)) echo json_encode(array('post'=>'empty'));
else echo json_encode($_POST+array('post'=>'not_empty'));
exit;
如果我将 content-type 标头(在 Swift 中)设置为 application/json,我会得到:
["post": empty]
empty
如果我将其设置为application/x-www-form-urlencoded,我会得到:
["{\"name\":\"thom\",\"password\":\"12345\"}": , "post": not_empty]
not_empty
如何将字典作为 $_POST 键/值对而不是 json_encoded 字符串发送到我的服务器?
【问题讨论】:
-
这对你来说可能很有趣stackoverflow.com/questions/40433229/…
-
这很有趣,但不确定它有什么帮助。我需要将参数字典作为键/值对传递给我的 $_POST 变量。如果我不在客户端对我的参数进行 json_encode,我会收到一条错误消息,提示我无法将类型 AnyObject 传递给类型数据?
-
我看过那个帖子。这就是我得到我的快速代码的地方(来自零票的答案)。我不想将查询字符串传递给服务器。我想通过字典。
-
获得
key=value字符串数组后,使用joined(separator: "&")将它们组合在一起。