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();
|