I am developing the client side of a web application in iOS/Swift, and right now I am testing the part that communicates with the server. I setup a basic website on localhost at:
http://localhost/~username/ConnectivityTest/login
(which corresponds to /Users/username/Sites/ConnectivityTest/login
on my Mac's file system).
The server side script (index.php
on the directory above) is:
<?PHP
$userId = $_POST["userId"];
$password = $_POST["password"];
if (empty($userId) || empty($password)){
echo "Error: empty post variables";
}
else{
// Process credentials...
I am using the NSURLSession
API on iOS, but I noticed that no matter how I configure my requests, even though the connection succeeds (i.e., returns an http code of 200 and the response body as data), the POST
variables are unavailable (empty) on the server side.
So I decided to try sending the request manually using Postman on the browser (to try to rule out any mistakes on my iOS/Swift code), but I don't know how I should configure it (I am not versed in HTTP, it all is still a bit confusing to me):
Should I set the
Content-Type
header toapplication/json
,application/x-www-form-urlencoded
, or what?Should I send the body data as
form-data
,x-www-form-urlencoded
orraw
?
In Postman, I set the body data (raw) as follows:
{
"userId":"my-user-name",
"password":"123456"
}
Alternativley, as form-data
, it is:
userId my-user-name [Text]
password 12345 [Text]
As x-www-form-urlencoded
, it is:
userId my-user-name
password 12345
Everything I try gives me the response "Error: empty post variables"
that I set in my code's error path (i.e., $_POST['userId']
or $_POST['password']
are empty).
If, instead, I pass the variables as URL parameters:
http://localhost/~username/ConnectivityTest/login/index.php?userId=my-user-name&password=12345
...and access them in the script as &_GET['userId']
and $_GET['password']
, it works fine.
what am I missing?
UPDATE: I created an HTML file in the same directory as the php file:
<html>
<body>
<form action="index.php" method="post">
User name: <input type="text" name="userId"><br>
Password: <input type="text" name="password"><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
If I load the above page in a browser, fill in the fields and submit the form, the $_POST
variables on my php script get the correct values. So the php code is correct, and I am setting up my request wrong in Postman (still don't know why).
UPDATE 2: Just in case there was a problem with localhost, I moved the script to a shared wb hosting service that I control, but the result is the same.
UPDATE 3: I must have missed it somehow before, but there is ONE setup that I got working:
Headers: Content-Type application/x-www-form-urlencoded
Body ("raw"): userId=my-user-name&password=123456
However, this restricts me to flat lists of key/value; If I wish to send more structured (i.e., nested) data to the server I need JSON support...