小编典典

使用Swift和API进行发布

swift

当我尝试向服务器上的API发送POST请求时遇到问题,我遵循了许多不同的教程,但仍然无法正常工作。我知道我的问题出在POST请求上,但我解决不了!所以这是我在Swift中的代码以及我在php中的API
:(是的,我已经用代码中的真实ID替换了xxxx)

总结一下,服务器接收到请求,例如,如果我手动输入一个伪指令,它就可以工作,实际上是POST方法不起作用。。服务器未接收到POST参数

SWIFT代码 :

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代码:

$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);

在此先感谢:)


阅读 297

收藏
2020-07-07

共1个答案

小编典典

试试这个:

 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()

您必须使用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)

我希望这可以帮助你!

2020-07-07