ech*_*ion 6 c# winforms .net-4.5
我的代码需要通过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();
Run Code Online (Sandbox Code Playgroud)
但是,我需要使用的GET不是POST.起初我以为解决办法是改变myRequest.Method = "POST";对GET,但这并没有工作,因为那不是如何GET工作,它从URL中提取数据.
那么,我试图将以前的代码更改为:
HttpwebRequest myRequest= (HttpWebRequest)WebRequest.Create("http://localhost/site.php" + postData);
Stream newStream = myRequest.GetRequestStream();
newStream.Close()
Run Code Online (Sandbox Code Playgroud)
根据它会调用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.
Run Code Online (Sandbox Code Playgroud)
任何帮助表示赞赏,谢谢.
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();
Run Code Online (Sandbox Code Playgroud)
或者甚至更简单:
var data = new WebClient().DownloadString("http://yourserver/site.php?var1=1&var2=2&var3=3");
Run Code Online (Sandbox Code Playgroud)
有关更多选项,请参阅WebClient类