2011-01-27 59 views
0

我有这个功能在C#中的女巫通过定时器称为每隔1分钟......如何使用的HttpWebRequest发送文本类在C#

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 [“书面记录”]
这样我就可以再处理文本,因为我想接受PHP的文字...

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

+0

我只在这里看到一个单一的问题 - “我应该打开和关闭”。还有哪些其他问题? – 2011-01-28 04:58:02

+0

我会摆脱try/catch。 – 2011-01-28 04:59:14

回答

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