Having stumbled upon a problem when doing this, I first searched SO to try and find if others were having similar problems, and found this question: POST data to a PHP page from C# WinForm
However, when I tried the code example given in the answer to this question, it does not work. The PHP script that I am making a request to responds with a message indicating that the POST variable that has to be set is not set. Here's my C# code:
HttpWebRequest POSTreq =
(HttpWebRequest)WebRequest.Create("http://82.41.255.140/api/post-ptr");
string POSTdata = "action=" + HttpUtility.UrlEncode("date");
byte[] data = Encoding.ASCII.GetBytes(POSTdata);
POSTreq.Method = "POST";
POSTreq.ContentType = "application/x-www-form-urlencoded";
POSTreq.ContentLength = data.LongLength;
POSTreq.GetRequestStream().Write(data, 0, data.Length);
HttpWebResponse POSTres = (HttpWebResponse)POSTreq.GetResponse();
Console.WriteLine("HTTP Status Code {0}", POSTres.StatusCode);
Console.WriteLine("Response Method: {0}", POSTres.Method);
Console.WriteLine("Response Text: {0}",
new StreamReader(POSTres.GetResponseStream()).ReadToEnd());
Console.ReadLine();
And this is the code inside the PHP script:
<?php
$A = strtolower($_POST["action"]);
if ($A == "date")
{
echo date("c");
}
else if ($A == "ip")
{
echo $_SERVER["REMOTE_ADDR"];
}
else if ($A == null || $A == "")
{
echo "bad_request:no_argument:POST_action";
}
else
{
echo "bad_request:invalid_argument:POST_action";
}
exit();
?>
When I make the POST request from my C# program, I see the following screen, indicating that the variable action
has not been set. Am I missing the obvious in my code?
Thanks to those who reply.