在C#中,是否可以在后台打开URL而无需打开浏览器?

我的代码需要通过php脚本向服务器提供一些信息。

基本上我想打电话给www.sitename.com/example.php?var1=1&var2=2&var3=3但是我不希望浏览器打开,所以Process.Start(URL); 不行。

由于我来到这个网站学习而不是得到答案,大多数情况下,我会解释到目前为止我所做的和我得到的错误。 如果您知道解决方案,请随意跳过下一部分。

我环顾四周,看到了使用POST的解决方案:

 ASCIIEncoding encoding=new ASCIIEncoding(); string postData="var1=1&var2=2&var3=3"; byte[] data = encoding.GetBytes(postData); // Prepare web request... HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create("http://localhost/site.php"); myRequest.Method = "POST"; myRequest.ContentType="application/x-www-form-urlencoded"; myRequest.ContentLength = data.Length; Stream newStream=myRequest.GetRequestStream(); // Send the data. newStream.Write(data,0,data.Length); newStream.Close(); 

但是,我要求使用GET而不是POST 。 起初我认为解决方案可能是更改myRequest.Method = "POST"; GET ,但这不起作用,因为这不是GET工作原理,它从URL中提取数据。

那么,我试图将以前的代码更改为:

 HttpwebRequest myRequest= (HttpWebRequest)WebRequest.Create("http://localhost/site.php" + postData); Stream newStream = myRequest.GetRequestStream(); newStream.Close() 

根据它会调用URL的逻辑,它会(希望)在php脚本上启动GET_请求,然后生活就会花花公子。 但是这会导致以下错误:

 A first chance exception of type 'System.Net.ProtocolViolationException' occurred in System.dll An unhandled exception of type 'System.Net.ProtocolViolationException' occurred in System.dll Additional information: Cannot send a content-body with this verb-type. 

任何帮助表示赞赏,谢谢。

 string postData="var1=1&var2=2&var3=3"; // Prepare web request... HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create( "http://yourserver/site.php?" + postData); myRequest.Method = "GET"; var resp =(HttpWebResponse) myRequest.GetResponse(); var result = new StreamReader(resp.GetResponseStream()).ReadToEnd(); 

或者甚至更简单:

 var data = new WebClient().DownloadString("http://yourserver/site.php?var1=1&var2=2&var3=3"); 

有关更多选项,请参阅WebClient类

你似乎大多走了正确的路线:

 string postData="var1=1&var2=2&var3=3"; // Prepare web request... HttpwebRequest myRequest= (HttpWebRequest)WebRequest.Create( "http://localhost/site.php?" + postData); // Send the data. myRequest.GetResponse(); 

请注意,我添加了?site.php

我们不必乱用请求流,因为这就是把事情放在请求的正文中 – 正如您所说的, GET请求的数据在URL中,而不是在其正文中。

最简单的方法是使用WebClient类。 使用它只需2行代码,只需提供您的URL并使用DownloadString方法。