WebApi系列~通過HttpClient來調用Web Api接口
HttpClient是一個被封裝好的類,主要用於Http的通訊,它在.net,java,oc中都有被實現,當然,我只會.net,所以,只講.net中的HttpClient去調用Web Api的方法,基於api項目的特殊性,它需要有一個完全安全的環境,所以,你的api控制器看起來有點特別,只有5個方法,而且都是標准的http方法,我覺得這種設計很不錯,很清晰,而且為了實現安全性,它不支持使用傳統的表單數據,取而代之的是FromBody參數,它指拿HttpRequestMessage里參數,而不是所有的Request數據,這是基於安全方面的考慮。
一 Api接口參數的標准性
Get方式,可以有多個重載,有多個參數
POST方式,只能有一個參數,並且用[FromBody]約束,如果有多個參數,需要以對象的方式進行傳遞
Put方式,只能有兩個參數,其中一個是通過Request.QueryString方式進行傳遞的,作為要更新對象的主鍵,別一個是[FromBody]字段,也是一個字段,如果多個字段需要把它封裝成對象
標准接口如圖
二 調用方,參數的標准性
在客戶端進行接口調用時,我們以網頁端為例,看一下網頁端進行ajax跨域請求的代碼
Get方式
$.ajax({
url: "http://localhost:52824/api/register",
type: "GET",
success: function (data) {
console.log("json:" + data);
}
});
Post方式
$.ajax({
url: "http://localhost:52824/api/register",
type: "POST",
data: { '': '1' },//這里鍵名稱必須為空,多個參數請傳對象,api端參數名必須為value
success: function (data) {
console.log("post:" + data);
}
});
三 在控制台中實現Get方式獲取接口數據(只有異步實現)
/// <summary>
/// HttpClient實現Get請求
/// </summary>
static async void dooGet()
{
string url = "http://localhost:52824/api/register?id=1&leval=5";
//創建HttpClient(注意傳入HttpClientHandler)
var handler = new HttpClientHandler() { AutomaticDecompression = DecompressionMethods.GZip };
using (var http = new HttpClient(handler))
{
//await異步等待回應
var response = await http.GetAsync(url);
//確保HTTP成功狀態值
response.EnsureSuccessStatusCode();
//await異步讀取最后的JSON(注意此時gzip已經被自動解壓縮了,因為上面的AutomaticDecompression = DecompressionMethods.GZip)
Console.WriteLine(await response.Content.ReadAsStringAsync());
}
}
四 在控制台中實現Post方式提交數據(只有異步實現)
/// <summary>
/// HttpClient實現Post請求
/// </summary>
static async void dooPost()
{
string url = "http://localhost:52824/api/register";
var userId = "1";
//設置HttpClientHandler的AutomaticDecompression
var handler = new HttpClientHandler() { AutomaticDecompression = DecompressionMethods.GZip };
//創建HttpClient(注意傳入HttpClientHandler)
using (var http = new HttpClient(handler))
{
//使用FormUrlEncodedContent做HttpContent
var content = new FormUrlEncodedContent(new Dictionary<string, string>()
{
{"", userId}//鍵名必須為空
});
//await異步等待回應
var response = await http.PostAsync(url, content);
//確保HTTP成功狀態值
response.EnsureSuccessStatusCode();
//await異步讀取最后的JSON(注意此時gzip已經被自動解壓縮了,因為上面的AutomaticDecompression = DecompressionMethods.GZip)
Console.WriteLine(await response.Content.ReadAsStringAsync());
}
}
五 在控制台中實現Put方式提交數據(只有異步實現)
/// <summary>
/// HttpClient實現Put請求
/// </summary>
static async void dooPut()
{
string url = "http://localhost:52824/api/register?userid=" + userId;
var userId = "1";
//設置HttpClientHandler的AutomaticDecompression
var handler = new HttpClientHandler() { AutomaticDecompression = DecompressionMethods.GZip };
//創建HttpClient(注意傳入HttpClientHandler)
using (var http = new HttpClient(handler))
{
//使用FormUrlEncodedContent做HttpContent
var content = new FormUrlEncodedContent(new Dictionary<string, string>()
{
{"", "數據"}//鍵名必須為空
});
//await異步等待回應
var response = await http.PutAsync(url, content);
//確保HTTP成功狀態值
response.EnsureSuccessStatusCode();
//await異步讀取最后的JSON(注意此時gzip已經被自動解壓縮了,因為上面的AutomaticDecompression = DecompressionMethods.GZip)
Console.WriteLine(await response.Content.ReadAsStringAsync());
}
}
OK,到這里,我們的客戶端如何去調用web api就講完了,事實上,手機端,平板端也是相關的方式去調用的,它們也都有自己的HttpClient類,大同小異!

