I can't figure out how to properly send POST parameters.
My 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()
My 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;
If I set the content-type header (in Swift) to application/json
I get:
["post": empty]
empty
If I set it to application/x-www-form-urlencoded
I get:
["{"name":"thom","password":"12345"}": , "post": not_empty]
not_empty
How do I send the dictionary to my server as $_POST key/value pairs, not as a json_encoded string?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…