如何使用后面的“ c#”代码调用网址

时间:2018-09-06 09:15:04

标签: c# http

如何在不打开浏览器的情况下打开链接?我需要使用预定义的链接发送回发

https://example.com/test?parm1=aaaa&parm2=1234

通常我会这样做:

Process.Start("https://example.com/test?parm1=aaaa&parm2=1234");

但是我需要在服务器上运行它,而无需打开浏览器。

2 个答案:

答案 0 :(得分:0)

您尝试这样做吗?

String url = "https://en.wikipedia.org/wiki/Sigiriya";

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "GET";
request.Timeout = Timeout.Infinite;
request.KeepAlive = true;

long length = 0;
try {               

    using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) {
        length = response.ContentLength;
        Stream dataStream = response.GetResponseStream();
        StreamReader reader = new StreamReader(dataStream);
        string responseFromServer = reader.ReadToEnd();
        Console.WriteLine(responseFromServer);                  
    }
} catch (Exception ex) {
   Console.WriteLine(ex);   
}

您也可以这样简单地拨打电话

var client = new WebClient();
var content = ient.DownloadString("https://en.wikipedia.org/wiki/Sigiriya");

答案 1 :(得分:0)

将您的所有信息汇总在一起,我将代码缩减为:

string link = "https://example.com/test?parm1=aaaa&parm2=1234";
WebRequest request = WebRequest.Create(link);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();

使用以下方法检查结果:

Console.WriteLine(response.StatusDescription);

谢谢你们的帮助!