Cru*_*lIO 46 c# get httpwebrequest
是否可以通过HTTP
get请求传递参数?如果是这样,我该怎么做呢?我找到了一个HTTP
帖子请求(链接).在该示例中,字符串postData
被发送到网络服务器.我想用get做同样的事情.谷歌发现,在这个例子中HTTP
得到这里.但是,没有参数发送到Web服务器.
wis*_*cky 125
我的首选方式是这样.它为您处理转义和解析.
WebClient webClient = new WebClient();
webClient.QueryString.Add("param1", "value1");
webClient.QueryString.Add("param2", "value2");
string result = webClient.DownloadString("http://theurl.com");
Run Code Online (Sandbox Code Playgroud)
Mar*_*ell 92
首先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);
}
Run Code Online (Sandbox Code Playgroud)
End*_*ssa 26
在GET请求中,您将参数作为查询字符串的一部分传递.
string url = "http://somesite.com?var=12345";
Run Code Online (Sandbox Code Playgroud)
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;
}
Run Code Online (Sandbox Code Playgroud)
将查询字符串参数(如果需要)添加为NameValueCollection,如下所示.
NameValueCollection QueryStringParameters = new NameValueCollection();
QueryStringParameters.Add("id", "123");
QueryStringParameters.Add("category", "A");
Run Code Online (Sandbox Code Playgroud)
将您的http标头(如果需要)添加为NameValueCollection,如下所示.
NameValueCollection RequestHttpHeaders = new NameValueCollection();
RequestHttpHeaders.Add("Authorization", "Basic bGF3c2912XBANzg5ITppc2ltCzEF");
Run Code Online (Sandbox Code Playgroud)
具有多个参数的 GET 请求:
curl --request GET --url http://localhost:8080/todos/ ?limit=10&offset=2 --header 'content-type:application/json'
归档时间: |
|
查看次数: |
171802 次 |
最近记录: |