在 C# 中,是否可以在不打开浏览器的情况下在后台打开 URL? [英] In C#, is it possible to open a URL in the background, without opening a browser?
问题描述
我的代码需要通过 php 脚本向服务器提供一些信息.
My code needs to supply some information to a server via a php script.
基本上我想调用 www.sitename.com/example.php?var1=1&var2=2&var3=3
但我不想打开浏览器,所以 Process.Start(URL);
不起作用.
Basically I want to call www.sitename.com/example.php?var1=1&var2=2&var3=3
but I don't want the browser to open, so Process.Start(URL);
won't work.
因为我来到这个网站是为了学习而不是为了得到答案,所以我将解释我到目前为止所做的事情以及我遇到的错误.如果您知道解决方案,请随时跳过下一部分.
Since I come to this site to learn and not to get answers, mostly, I will explain what I've done so far and the errors I have gotten. If you know a solution anyway, feel free to skip the next part.
我环顾四周,看到了一个使用 POST 的解决方案:
I have looked around, and I saw a solution for using 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 中提取数据.
However, I require the use of GET
not POST
. At first I thought the solution might be to change myRequest.Method = "POST";
to GET
, but this didn't work because that's not how GET
works, it pulls data from the URL.
所以,然后我尝试将之前的代码更改为:
So, then I attempted to change the previous code to:
HttpwebRequest myRequest= (HttpWebRequest)WebRequest.Create("http://localhost/site.php" + postData);
Stream newStream = myRequest.GetRequestStream();
newStream.Close()
在它会调用 URL 的逻辑下,它会(希望)在 php 脚本上发起 GET_ 请求,然后生活就会变得很花哨.然而,这导致了以下错误:
Under the logic that it would call the URL, which would (hopefully) initiate the GET_ request on the php script, and then life would be dandy. This however resulted in the following error:
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 类更多选择
这篇关于在 C# 中,是否可以在不打开浏览器的情况下在后台打开 URL?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!