使用swift和API进行POST [英] POST with swift and API
问题描述
当我尝试向我的服务器上的API发送POST请求时遇到问题,我已经遵循了许多不同的教程,但它仍然无法正常工作。
我知道我的问题与POST请求有关但我无法解决!
所以这是我在Swift中的代码和我在php中的API :(是的,我已经用代码中的真实ID替换了xxxx)
To总结服务器接收请求,例如,如果我手动输入伪它工作,它真的是POST方法谁不工作..服务器没有收到POST参数
Swift代码:
var request = NSMutableURLRequest(URL:NSURL(字符串:http:// localhost:8888 /academy/test.php)!)
var session = NSURLSession.sharedSession()
request.HTTPMethod =POST
var params = [pseudo: test] as Dictionary< String,String>
var err:NSError?
request.HTTPBody = NSJSONSerialization.dataWithJSONObject(params,options:nil,error:& err)
request.addValue(application / json,forHTTPHeaderField:Content-Type)
request.addValue(application / json,forHTTPHeaderField:Accept)
var task = session.dataTaskWithRequest(request,completionHandler:{data,response,error - > Void in
println(Response:\(response))
var strData = NSString(data:data,encoding:NSUTF8StringEncoding)
println(Body:\(strData))
var错误:NSError?
var json = NSJSONSerialization.JSONObjectWithData(data,options:.MutableLeaves,error:& err)as?NSDictionary
// JSONObjectWithData构造函数是否返回错误?所以,将错误记录到控制台
if(err!= nil){
println(err!.localizedDescription)
let jsonStr = NSString(data:data,encoding:NSUTF8StringEncoding)
println(错误无法解析JSON:'\(jsonStr)')
}
else {
// JSONObjectWithData构造函数未返回错误。但是,我们仍然应该
//检查并确保json具有使用可选绑定的值。
如果让parseJSON = json {
//好吧,解析的JSON就在这里,让我们从它获得'成功'的值
var success = parseJSON [success]为? Int
println(成功:\(成功))
}
else {
// Woa,好吧,json对象是零,有些事情发生了。也许服务器没有运行?
let jsonStr = NSString(data:data,encoding:NSUTF8StringEncoding)
println(Error无法解析JSON:\(jsonStr))
}
}
})
task.resume()* /
PHP代码:
$ BDD_hote ='xxxxx';
$ BDD_bd ='xxxxx';
$ BDD_utilisateur ='xxxxx';
$ BDD_mot_passe ='xxxxx';
try {
$ bdd = new PDO('mysql:host ='。$ BDD_hote。'; dbname ='。$ $ BDD_bd,$ BDD_utilisateur,$ BDD_mot_passe);
$ bdd-> exec(SET CHARACTER SET utf8);
$ bdd-> setAttribute(PDO :: ATTR_ERRMODE,PDO :: ERRMODE_WARNING);
}
catch(PDOException $ e){
echo'Erreur:'。$ e-> getMessage();
echo'N°:'。$ e-> getCode();
}
$ pseudo = addslashes($ _ POST [pseudo]);
$ req = $ bdd-> query(SELECT * from users WHERE pseudo ='$ pseudo');
$ resultArray = array();
$ donnees = $ req-> fetch();
echo json_encode($ donnees);
感谢提前:)
让myURL = NSURL(字符串:http:// localhost: 8888 /学院/ test.php的)!
let request = NSMutableURLRequest(URL:myURL)
request.HTTPMethod =POST
request.setValue(application / x-www-form-urlencoded,forHTTPHeaderField:Content-Type )
request.setValue(application / json,forHTTPHeaderField:Accept)
let bodyStr:String =pseudo = test
request.HTTPBody = bodyStr.dataUsingEncoding(NSUTF8StringEncoding)
let task = NSURLSession.sharedSession()。dataTaskWithRequest(request){
data,response,error in
//你的完成处理程序代码在这里
}
task.resume()
您必须使用UTF8字符串编码对数据进行编码。如果您需要为请求正文设置多个字段和值对,则可以更改正文字符串,例如pseudo = test& language = swift。实际上,我通常会为NSMutableURLRequest创建一个扩展,并添加一个方法,该方法将字典作为参数,并使用正确的编码将此地图(字典)的内容设置为HTTPBody。这可能对你有用:
extension NSMutableURLRequest {
func setBodyContent(contentMap:Dictionary< String,String>){
var firstOneAdded = false
let contentKeys:Array< String> = array(contentMap.keys)
for contentKey in contentKeys {
if(!firstOneAdded){
contentBodyAsString + = contentKey +=+ contentMap [contentKey]!
firstOneAdded = true
}
else {
contentBodyAsString + =& + contentKey +=+ contentMap [contentKey]!
}
}
contentBodyAsString = contentBodyAsString.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)!
self.HTTPBody = contentBodyAsString.dataUsingEncoding(NSUTF8StringEncoding)
}
}
您可以将其用作:
request.setBodyContent(params)
我希望这可以帮到你!
I've a problem when I try to send a POST request to my API on my server, I've followed many many different tutorials but it still doesn't work. I know than my problem is with the POST request but I can't solve it ! So this is my code in Swift and my API in php : (and yes I've replaced the xxxx by the real IDs in my code)
To sum up server receive the request and for example if I manually enter a pseudo it works, It's really the POST method who doesn't work.. The server doesn't receive the POST parameter
Swift code :
var request = NSMutableURLRequest(URL: NSURL(string: "http://localhost:8888/academy/test.php")!)
var session = NSURLSession.sharedSession()
request.HTTPMethod = "POST"
var params = ["pseudo":"test"] as Dictionary<String, String>
var err: NSError?
request.HTTPBody = NSJSONSerialization.dataWithJSONObject(params, options: nil, error: &err)
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
var task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in
println("Response: \(response)")
var strData = NSString(data: data, encoding: NSUTF8StringEncoding)
println("Body: \(strData)")
var err: NSError?
var json = NSJSONSerialization.JSONObjectWithData(data, options: .MutableLeaves, error: &err) as? NSDictionary
// Did the JSONObjectWithData constructor return an error? If so, log the error to the console
if(err != nil) {
println(err!.localizedDescription)
let jsonStr = NSString(data: data, encoding: NSUTF8StringEncoding)
println("Error could not parse JSON: '\(jsonStr)'")
}
else {
// The JSONObjectWithData constructor didn't return an error. But, we should still
// check and make sure that json has a value using optional binding.
if let parseJSON = json {
// Okay, the parsedJSON is here, let's get the value for 'success' out of it
var success = parseJSON["success"] as? Int
println("Succes: \(success)")
}
else {
// Woa, okay the json object was nil, something went worng. Maybe the server isn't running?
let jsonStr = NSString(data: data, encoding: NSUTF8StringEncoding)
println("Error could not parse JSON: \(jsonStr)")
}
}
})
task.resume()*/
PHP Code :
$BDD_hote = 'xxxxx';
$BDD_bd = 'xxxxx';
$BDD_utilisateur = 'xxxxx';
$BDD_mot_passe = 'xxxxx';
try{
$bdd = new PDO('mysql:host='.$BDD_hote.';dbname='.$BDD_bd, $BDD_utilisateur, $BDD_mot_passe);
$bdd->exec("SET CHARACTER SET utf8");
$bdd->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);
}
catch(PDOException $e){
echo 'Erreur : '.$e->getMessage();
echo 'N° : '.$e->getCode();
}
$pseudo = addslashes($_POST["pseudo"]);
$req = $bdd->query("SELECT * from users WHERE pseudo='$pseudo'");
$resultArray = array();
$donnees = $req->fetch();
echo json_encode($donnees);
Thanks by advance :)
Try this:
let myURL = NSURL(string: "http://localhost:8888/academy/test.php")!
let request = NSMutableURLRequest(URL: myURL)
request.HTTPMethod = "POST"
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
request.setValue("application/json", forHTTPHeaderField: "Accept")
let bodyStr:String = "pseudo=test"
request.HTTPBody = bodyStr.dataUsingEncoding(NSUTF8StringEncoding)
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
data, response, error in
// Your completion handler code here
}
task.resume()
You have to encode your data using UTF8 string encoding. If you need to set more than one field&value pairs for request body, you can change the body string, for example, "pseudo=test&language=swift". In fact, I usually create an extension for NSMutableURLRequest and add a method which takes a dictionary as parameter and sets the content of this map(dictionary) as HTTPBody using correct encoding. This may work for you:
extension NSMutableURLRequest {
func setBodyContent(contentMap: Dictionary<String, String>) {
var firstOneAdded = false
let contentKeys:Array<String> = Array(contentMap.keys)
for contentKey in contentKeys {
if(!firstOneAdded) {
contentBodyAsString += contentKey + "=" + contentMap[contentKey]!
firstOneAdded = true
}
else {
contentBodyAsString += "&" + contentKey + "=" + contentMap[contentKey]!
}
}
contentBodyAsString = contentBodyAsString.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)!
self.HTTPBody = contentBodyAsString.dataUsingEncoding(NSUTF8StringEncoding)
}
}
And you can use this as:
request.setBodyContent(params)
I hope this helps you!
这篇关于使用swift和API进行POST的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!