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 方式获取接口数据(只有异步实现)
///
/// HttpClient 实现 Get 请求
///
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 方式提交数据(只有异步实现)
///
/// HttpClient 实现 Post 请求
///
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()
{
{"", 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 方式提交数据(只有异步实现)
///
/// HttpClient 实现 Put 请求
///
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()
{
{"", "数据"}//键名必须为空
});
//await 异步等待回应
var response = await http.PutAsync(url, content);
//确保 HTTP 成功状态值
response.EnsureSuccessStatusCode();
//await 异步读取最后的 JSON(注意此时 gzip 已经被自动
解压缩了,因为上面的 AutomaticDecompression =
DecompressionMethods.GZip)
Console.WriteLine(await
response.Content.ReadAsStringAsync());
}
}