如何在C#中使用HttpWebRequest类发送文本

时间:2011-01-27 14:54:34

标签: c# httpwebrequest

我在C#中有这个功能,每1分钟通过一个计时器调用一次......

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 = "";
}

编写此代码以执行下一步:

检查网站是否有连接...
如果有一个,那么...将'writeup'字符串变量中的文本发送到存储在站点根目录中的'save.php'文件...
写入字符串将使用“POST”方法(而不是“Get”方法)发布到php文件... ... 所以我可以通过变量$ _POST ['writeup']来接受PHP中的文本 所以我可以随意处理文本......

更多问题...... 女巫每分钟更好地打开和关闭httprequest ...或者在互联网连接可用时保持打开...

1 个答案:

答案 0 :(得分:1)

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 = "";
}