如何使用参数进行HTTP获取请求

有可能通过HTTP获取请求传递参数吗? 如果是的话,我该怎么做呢? 我find了一个HTTP POST请求( 链接 )。 在这个例子中,stringpostData被发送到一个web服务器。 我想用相同的方式做同样的事情 。 Google在HTTP上find这个例子。 但是没有参数被发送到Web服务器。

在GET请求中,您将参数作为查询string的一部分传递。

 string url = "http://somesite.com?var=12345"; 

第一个WebClient更容易使用; 在查询string上指定GET参数 – 唯一的技巧是记住转义任何值:

  string address = string.Format( "http://foobar/somepage?arg1={0}&arg2={1}", Uri.EscapeDataString("escape me"), Uri.EscapeDataString("& me !!")); string text; using (WebClient client = new WebClient()) { text = client.DownloadString(address); } 

我最喜欢的方式是这个。 它处理你的转义和parsing。

 WebClient webClient = new WebClient(); webClient.QueryString.Add("param1", "value1"); webClient.QueryString.Add("param2", "value2"); string result = webClient.DownloadString("http://theurl.com"); 

WebRequest对象似乎对我来说太多了。 我更喜欢使用WebClient控件。

要使用这个函数,你只需要创build两个NameValueCollections来存放你的参数和请求头。

考虑以下function:

  private static string DoGET(string URL,NameValueCollection QueryStringParameters = null, NameValueCollection RequestHeaders = null) { string ResponseText = null; using (WebClient client = new WebClient()) { try { if (RequestHeaders != null) { if (RequestHeaders.Count > 0) { foreach (string header in RequestHeaders.AllKeys) client.Headers.Add(header, RequestHeaders[header]); } } if (QueryStringParameters != null) { if (QueryStringParameters.Count > 0) { foreach (string parm in QueryStringParameters.AllKeys) client.QueryString.Add(parm, QueryStringParameters[parm]); } } byte[] ResponseBytes = client.DownloadData(URL); ResponseText = Encoding.UTF8.GetString(ResponseBytes); } catch (WebException exception) { if (exception.Response != null) { var responseStream = exception.Response.GetResponseStream(); if (responseStream != null) { using (var reader = new StreamReader(responseStream)) { Response.Write(reader.ReadToEnd()); } } } } } return ResponseText; } 

像这样,将你的查询string参数(如果需要的话)作为NameValueCollection添加。

  NameValueCollection QueryStringParameters = new NameValueCollection(); QueryStringParameters.Add("id", "123"); QueryStringParameters.Add("category", "A"); 

像这样添加你的http头(如果需要)作为NameValueCollection。

  NameValueCollection RequestHttpHeaders = new NameValueCollection(); RequestHttpHeaders.Add("Authorization", "Basic bGF3c2912XBANzg5ITppc2ltCzEF"); 

您也可以通过URL直接传递值。

如果你想调用方法public static void calling(string name){....}

那么你应该使用HttpWebRequest webrequest = (HttpWebRequest)WebRequest.Create("http://localhost:****/Report/calling?name=Priya); webrequest.Method = "GET"; webrequest.ContentType = "application/text";调用HttpWebRequest webrequest = (HttpWebRequest)WebRequest.Create("http://localhost:****/Report/calling?name=Priya); webrequest.Method = "GET"; webrequest.ContentType = "application/text";

只要确保在URL中使用?Object = value