开发者

how to send text using HttpWebRequest class in C#

I have this function in C# witch is called via a timer every 1 minute...

private void timer1_Tick(object sender, EventArgs e)

{
    string strServer = "hhttp://www.mydomain.net/save.php";
    try {
        HttpWebRequest reqFP = (HttpWebRequest)HttpWebRequest.Create(strServer);
        HttpWebResponse rspFP = (HttpWebResponse)reqFP.GetResponse();
        if (rspFP.StatusCode == HttpStatusCode.OK) { // ther is an internet connection
            //send the text stored in 'writeUp' string variable to the url via 'POST' methode
            rspFP.Close(); //is good to open and close the connection every minute
        }
    }
    catch (WebException) {
        //I don't know why to use try/catch... but I just don't want any errors to be poped up...
    }
    writeUp = "";
}

this code is written to do the next:

check if there's a connection to the site...

if there's a one, then... send the text from the 'writeup' string variable to the 'save.php' file stored in the root of the site...

where the writeup string will be posted to the php file using 'POST' method (instead of 'Get' method)...

so I can accept the text in PHP via the variable $_POST['writeup']

so i can then process the text as I want...

more questions... witch better open and close the 开发者_开发百科httprequest every minute... or keep it open all the time the internet connection is available...


private void timer1_Tick(object sender, EventArgs e)    
{
    string strServer = "hhttp://www.mydomain.net/save.php";
    try 
    {
        var reqFP = (HttpWebRequest)HttpWebRequest.Create(strServer);

        reqFP.Method = "POST";
        reqFP.ContentType = "application/x-www-form-urlencoded";

        reqFP.ContentLength = writeup.Length;

        /*var rspFP = (HttpWebResponse)reqFP.GetResponse();
        if (rspFP.StatusCode == HttpStatusCode.OK) 
        {*/
            //WRITE STRING TO STREAM HERE
            using (var sw = new StreamWriter(reqFP.GetRequestStream(), Encoding.ASCII))
            {
                sw.Write(writeup);
            }   

            rspFP.Close(); //is good to open and close the connection every minute
        /*}*/       
    }
    catch (WebException) {
        //I don't know why to use try/catch... 
        //but I just don't want any errors to be poped up...
    }
    writeUp = "";
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜