PHP Web服务无法识别Swift POST请求

时间:2019-03-01 01:16:56

标签: php mysql swift

点击带有一些代码的按钮后,我正在向MySQL Web服务创建一个Swift POST请求。但是,我没有获得所需的预期结果。每当我尝试将$ _POST变量传递给php webservice时,我的mysqli_query始终不对发布变量返回任何信息。

我在Swift和MySQL中都进行了故障排除,这是我得到的结果。

在Swift中,使用打印:

["error": Invalid username and/or password., "password": <null>, "username": <null>, "allData": {
    "{\n__\"username\"_:_\"Test_User\",\n__\"password\"_:_\"testuser\"\n}" = "";
}]

如此处所示,密码和用户名均为null,但是当我尝试将所有post参数包含在从php web服务返回的json对象中时,可以看到我以以下格式传递了该参数:我不确定(例如“ allData”:{     “ {\ n __ \”用户名\“ \” Test_User \“),...

这是我目前在视图控制器上的代码:

@IBAction func signinTapped(_ sender: Any) {

        // Read values from login text fields
        let loginUsrVar = loginUsr.text
        let loginPwdVar = loginPwd.text

        let urlPath = URL(string: "https://website.com/WebServices/CheckUser.php")
        var request = URLRequest(url: urlPath!)
        request.httpMethod = "POST"
        request.addValue("application/json", forHTTPHeaderField: "content/type")
        request.addValue("application/json", forHTTPHeaderField: "Accept")

        let postString = ["username": loginUsrVar!, "password": loginPwdVar!] as [String:String]

        let postString:NSDictionary = ["username": loginUsrVar!, "password": loginPwdVar!]
        print("postString:", postString)

        do {
            request.httpBody = try JSONSerialization.data(withJSONObject: postString, options: .prettyPrinted)
            print("JSON Serialization successful.")
            print(request)  
        } catch let error {
            print(error.localizedDescription)
            displayMessage(userMessage: "Something went wrong during the login process...")
            return
        }


        let task = URLSession.shared.dataTask(with: request) { (data: Data?, response: URLResponse?, error: Error?) in

            if error != nil {
                self.displayMessage(userMessage: "Could not successfully perform  the request. Please try again later.")
                return
            }

            print("data sent:", data)
            print("successful response:", response)

            let dataTransformed = NSString(data: request.httpBody!, encoding:String.Encoding.utf8.rawValue)!

            print("response encoded:", dataTransformed)

            do {
                let jsonResult = try JSONSerialization.jsonObject(with: data!, options: [.mutableContainers]) as? NSDictionary
                if let jsonResult = jsonResult as? [String: Any] {
                    print(jsonResult)
                }
            } catch {
                self.displayMessage(userMessage: "Could not successfully perform this request. Please try again later.")
            }


        }
        task.resume()
    }

我正在使用Web服务通过以下php代码提取应用程序所需的数据:

<?php
// header("Content-Type: application/json");
// Create connection
$con=mysqli_connect("database_address","username","password","current_app");

// Check connection
if (mysqli_connect_errno())
{
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

// This SQL statement selects ALL from the table 'Locations'
$sql = "SELECT * FROM users WHERE username='" . $_POST["username"] . "' and password = '". $_POST["password"]."'";
// $sql = "SELECT * FROM users WHERE username='Test User 1' and password = 'testuser'";

// Check if there are results
  if ($result = mysqli_query($con, $sql))
  {
    $count = mysqli_num_rows($result);

    if ($count == 0 ) {                                                         // If no users are found with sql query
      // echo "Invalid username and/or password.";
      $msg -> error = "Invalid username and/or password.";
      $msg -> username = $_POST["username"];
      $msg -> password = $_POST["password"];
      $msg -> allData = $_POST;
      echo json_encode($msg, JSON_UNESCAPED_SLASHES);
      // echo $_POST["username"];
    } else {                                                             

      $msg -> greeting = "hello";
      $msg -> otherData = $_POST;

      echo json_encode($msg);
    }
  }

// Close connections
mysqli_close($con);
?>

我的问题是,如何正确提取供Web服务使用的post变量?

0 个答案:

没有答案