Reputation: 4207
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.
Upvotes: 1
Views: 2502
Reputation: 4207
I've found the problem.
It turns out I'd left off the trailing /
in the request, and the request was getting 301'd, which for whatever reason removed the post variables.
So http://82.41.255.140/api/post-ptr
should have been http://82.41.255.140/api/post-ptr/
.
Thanks to everyone who answered, I've +1'd you all.
Upvotes: 0
Reputation: 241525
You're not closing the request stream. See this example in the MSDN docs, which is very close to your code.
EDIT
Your PHP null check is incorrect also. See this article.
Upvotes: 2
Reputation: 29668
You might need to flush the stream. I usually do it like this:
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;
using (Stream stream = POSTreq.GetRequestStream()) {
stream.Write(data, 0, data.Length);
stream.Flush();
}
Upvotes: 4