views:

119

answers:

4

i have used following code in my c# application

string verification_url = @"http://site.com/posttest.php?";
string verification_data = "test=524001A";
string result = string.Empty;
result = Post(verification_url, verification_data);

public string Post(string url, string data)
{
    string result = "";
    try
    {
        byte[] buffer = Encoding.GetEncoding(1252).GetBytes(data);
        HttpWebRequest WebReq = (HttpWebRequest)WebRequest.Create(@url);
        WebReq.Method = "POST";

        WebReq.ContentType = "application/x-www-form-urlencoded";              
        WebReq.ContentLength = buffer.Length;
        Stream PostData = WebReq.GetRequestStream();

        PostData.Write(buffer, 0, buffer.Length);
        PostData.Close();

        HttpWebResponse WebResp = (HttpWebResponse)WebReq.GetResponse();
        Stream Answer = WebResp.GetResponseStream();
        StreamReader _Answer = new StreamReader(Answer);
        result = _Answer.ReadToEnd();
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
    if (result.Length < 0)
    result = "";

    return result;

}

Server side PHP code

<?php   
$test=$_REQUEST['test'];
echo $test;
?>

post method always returns empty value

please help me

+1  A: 

try

<?php
print_r($_REQUEST);
?>

to show the raw REQUEST vars. im not sure where you setting test in your c# code.

Rufinus
print_r outputArray()
JKS
check the accesslogs, my guess is the request is not hiting the server. maybe Tudor Olariu's ".net permission" is the key to your problem.
Rufinus
A: 

You need to add the verification data as parameter to the request url eg.

string verification_data = "test=524001A";
string verification_url = @"http://site.com/posttest.php?" + verification_data;

That way your actual request URL would be:

http://site.com/posttest.php?test=524001A
Dan Diplo
but this would just be a get request, for what is he setting the contenttype/length headers.
Rufinus
No it wouldn't. He is setting WebReq.Method = "POST" and also the encoding is "application/x-www-form-urlencoded". Trust me, it will POST the data in the querystring, I've done this before.
Dan Diplo
it was my fortune to not need c#. if you say it will work, i belive you. it just looks strange to me.
Rufinus
A: 

Could you try not closing the RequestStream? Try removing the following line:

PostData.Close();

PS: Do you have the necessary .net permissions to do this?

Tudor Olariu
i have removed the above said line still getting empty result
JKS
A: 

i have changed the following line

string verification_url = @"http://site.com/posttest.php?";

to

string verification_url = @"http://www.site.com/posttest.php?";

it now works fine

JKS