是否可以通过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