是否可以通過HTTP
獲取請求傳遞參數?如果是這樣,那我應該怎麼做呢?我找到了一份HTTP
郵寄要求(link)。在那個例子中,字符串postData
被髮送到一個網絡服務器。我想用來代替。谷歌在HTTP
上找到這個例子得到here。但是沒有參數被髮送到Web服務器。如何使用參數進行HTTP獲取請求
37
A
回答
17
在GET請求中,您將參數作爲查詢字符串的一部分傳遞。
string url = "http://somesite.com?var=12345";
85
第一個WebClient
更容易使用; 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);
}
93
我的首選方法是這樣的。它爲你處理轉義和解析。
WebClient webClient = new WebClient();
webClient.QueryString.Add("param1", "value1");
webClient.QueryString.Add("param2", "value2");
string result = webClient.DownloadString("http://theurl.com");
6
WebRequest對象對我來說似乎太多了。我更喜歡使用WebClient控件。
要使用此函數,只需創建兩個NameValueCollections來存放參數和請求標頭。
考慮以下功能:
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;
}
添加您的查詢字符串參數(如果需要)像這樣一個NameValueCollection中。
NameValueCollection QueryStringParameters = new NameValueCollection();
QueryStringParameters.Add("id", "123");
QueryStringParameters.Add("category", "A");
把你的http頭(如果需要的話)作爲NameValueCollection添加如此。
NameValueCollection RequestHttpHeaders = new NameValueCollection();
RequestHttpHeaders.Add("Authorization", "Basic bGF3c2912XBANzg5ITppc2ltCzEF");
0
您也可以直接通過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";
只要確保你在URL
如果您輸入完整的網址,包括在住址的參數使用
?Object = value
iexplore的酒吧,然後我得到了同樣的迴應,是從C#提出的http請求得到的# – CruelIO 2009-02-05 09:05:03應該是這樣的。 – EndangeredMassa 2009-02-05 15:22:51