.NET/C#发起GET和POST请求的几种方法
using System.Net;
|
GET:
1
2
3
|
var request = (HttpWebRequest)WebRequest.Create("http://www.leadnt.com/recepticle.aspx");
var response = (HttpWebResponse)request.GetResponse();
var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
|
POST:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
var request = (HttpWebRequest)WebRequest.Create("http://www.leadnt.com/recepticle.aspx");
var postData = "thing1=hello";
postData += "&thing2=world";
var data = Encoding.ASCII.GetBytes(postData);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = data.Length;
using (var stream = request.GetRequestStream())
{
stream.Write(data, 0, data.Length);
}
var response = (HttpWebResponse)request.GetResponse();
var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
|
第二种:WebClient,也过时了:
1
2
|
using System.Net;
using System.Collections.Specialized;
|
GET:
1
2
3
4
|
using (var client = new WebClient())
{
var responseString = client.DownloadString("http://www.leadnt.com/recepticle.aspx");
}
|
POST:
1
2
3
4
5
6
7
8
9
10
|
using (var client = new WebClient())
{
var values = new NameValueCollection();
values["thing1"] = "hello";
values["thing2"] = "world";
var response = client.UploadValues("http://www.leadnt.com/recepticle.aspx", values);
var responseString = Encoding.Default.GetString(response);
}
|
第三种:HttpClient 当前主流用法,异步请求,自.NET4.5开始可从Nuget包管理中获取。
1
|
using System.Net.Http;
|
GET:
1
2
3
4
|
using (var client = new HttpClient())
{
var responseString = client.GetStringAsync("http://www.mydomain.com/recepticle.aspx");
}
|
POST:
1
2
3
4
5
6
7
8
9
10
11
12
|
using (var client = new HttpClient())
{
var values = new List<KeyValuePair<string, string>>();
values.Add(new KeyValuePair<string, string>("thing1", "hello"));
values.Add(new KeyValuePair<string, string>("thing2 ", "world"));
var content = new FormUrlEncodedContent(values);
var response = await client.PostAsync("http://www.mydomain.com/recepticle.aspx", content);
var responseString = await response.Content.ReadAsStringAsync();
}
|
第四种:第三方类库:
REST API请求测试类库,可通过 NuGet 获得。
最新的便捷的api测试工具,使用HttpClient实现,可通过 NuGet 安装。
1
|
using Flurl.Http;
|
GET:
1
2
|
var responseString = await "http://www.mydomain.com/recepticle.aspx"
.GetStringAsync();
|
POST:
1
2
3
|
var responseString = await "http://www.mydomain.com/recepticle.aspx"
.PostUrlEncodedAsync(new { thing1 = "hello", thing2 = "world" })
.ReceiveString();
|