[C#.NET][Web API] 調用 Server 功能
紀錄 HttpWebRequest、WebClient、HttpClient 調用 Server 的方式
由於 Web API 所實作出來的服務沒有 metadata,所以我們沒有辦法使用『加入Web參考』讓其他 .NET 開發人員直接引用,我們必須使用 HttpWebRequest、WebClient 、 HttpClient 來存取資料,接下來馬上實作
準備工具 Json.NET
因為 Proxy 的關係我的 NuGet 不能用,所以我以下範例我使用 JavaScriptSerializer
HttpWebRequest、WebClient .NET 2.0 就已經支援
JavaScriptSerializer 則是.NET 3.5 才開始支援
HttpClient 則是.NET4.5 .NET 4.0 才有的產物
本篇則針對 get/post 進行實作
實作內容如下:
HttpWebRequest
WebClient
HttpClient
HttpWebRequest
GET
private void useHttpWebRequest_Get()
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://localhost:64365/api/products");
request.Method = WebRequestMethods.Http.Get;
request.ContentType = "application/json";
using (var response = (HttpWebResponse)request.GetResponse())
{
if (response.StatusCode == HttpStatusCode.OK)
{
using (var stream = response.GetResponseStream())
using (var reader = new StreamReader(stream))
{
var temp = reader.ReadToEnd();
//TODO:反序列化
var serializer = new JavaScriptSerializer();
var list = serializer.Deserialize<List<Product>>(temp);
this.dataGridView1.DataSource = list;
this.txtResponse.Text = temp;
}
}
else
{
this.dataGridView1.DataSource = null;
}
}
}
POST
private void useHttpWebRequest_Post()
{
//TODO:序列化
var serializer = new JavaScriptSerializer();
var jsonText = serializer.Serialize(new Product() { ISBN = "1234" });
var jsonBytes = Encoding.UTF8.GetBytes(jsonText);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://localhost:64365/api/products");
request.Method = WebRequestMethods.Http.Post;
request.ContentType = "application/json";
request.ContentLength = jsonBytes.Length;
using (var requestStream = request.GetRequestStream())
{
requestStream.Write(jsonBytes, 0, jsonBytes.Length);
requestStream.Flush();
}
using (var response = (HttpWebResponse)request.GetResponse())
{
using (var stream = response.GetResponseStream())
using (var reader = new StreamReader(stream))
{
var result = reader.ReadToEnd();
MessageBox.Show(result);
}
}
}
WebClient
GET
private void useWebClient_Get()
{
WebClient client = new WebClient();
client.Encoding = Encoding.UTF8; client.Headers.Add(HttpRequestHeader.ContentType, "application/json");
var body = client.DownloadString("http://localhost:64365/api/products");
//TODO:反序列化
var serializer = new JavaScriptSerializer();
var list = serializer.Deserialize<List<Product>>(body);
this.dataGridView1.DataSource = list;
this.txtResponse.Text = body;
}
POST
private void useWebClient_Post()
{
//TODO:序列化
var serializer = new JavaScriptSerializer();
var product = new Product() { ISBN = "222" };
var jsonText = serializer.Serialize(product);
WebClient client = new WebClient();
client.Encoding = Encoding.UTF8;
client.Headers.Add(HttpRequestHeader.ContentType, "application/json");
var response = client.UploadData("http://localhost:64365/api/products", "POST", Encoding.UTF8.GetBytes(jsonText));
MessageBox.Show(Encoding.UTF8.GetString(response));
}
HttpClient
HttpClient 使用 TAP 非同步模組,回傳 Task<HttpResponseMessage> 詳細用法請參考 http://www.dotblogs.com.tw/yc421206/category/9208.aspx
GET
private void useHttpClient_Get()
{
var client = new HttpClient();
client.BaseAddress = new Uri("http://localhost:64365/");
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var response = client.GetAsync("api/products").Result;
var body = response.Content.ReadAsStringAsync().Result;
//TODO:反序列化
var serializer = new JavaScriptSerializer();
var list = serializer.Deserialize<List<Product>>(body);
this.dataGridView1.DataSource = list;
this.txtResponse.Text = body;
}
POST
private void useHttpClient_Post()
{
var serializer = new JavaScriptSerializer();
var product = new Product {ISBN = "1234"};
var jsonText = serializer.Serialize(product);
var client = new HttpClient();
client.BaseAddress = new Uri("http://localhost:64365/");
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
StringContent content = new StringContent(jsonText, Encoding.UTF8, "application/json");
var response = client.PostAsync("api/products", content).Result;
string responseBody = response.Content.ReadAsStringAsync().Result;
MessageBox.Show(responseBody);
}
在.NET4.5 4.0 裡新增了 System.Net.Http.HttpContentExtensions 它主要是增加一些擴充功能,比如 PostAsJsonAsync
這可以省掉序列化的動作,不過調用 PostAsJsonAsync 處理 json 序列化資料,不過也是需要 Json.NET,參考:http://www.asp.net/web-api/overview/web-api-clients/calling-a-web-api-from-a-net-client
測試
POST
文章出自:https://www.dotblogs.com.tw/yc421206/2013/11/11/127593
參考來源:http://www.asp.net/web-api/overview/web-api-clients/calling-a-web-api-from-a-net-client
範例下載:http://yunpan.cn/Q9bDWKAMgZTf4
若有謬誤,煩請告知,新手發帖請多包涵
Microsoft MVP Award 2010~2017 C# 第四季
Microsoft MVP Award 2018~2022 .NET