c# 【MVC】WebApi通过HttpClient来调用Web Api接口

/// <summary>
/// HttpClient实现Post请求(异步)
/// </summary>
static async void dooPost()
{
	string url = "http://localhost:52824/api/register";
	 //设置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>()       
		{    {"Id","6"},
			 {"Name","添加zzl"},
			 {"Info", "添加动作"}//键名必须为空
		 });

		//await异步等待回应

		var response = await http.PostAsync(url, content);
		//确保HTTP成功状态值
		response.EnsureSuccessStatusCode();
		//await异步读取最后的JSON(注意此时gzip已经被自动解压缩了,因为上面的AutomaticDecompression = DecompressionMethods.GZip)
		Console.WriteLine(await response.Content.ReadAsStringAsync());
	}

}
/// <summary>
/// HttpClient实现Get请求(异步)
/// </summary>
static async void dooGet()
{
	string url = "http://localhost:52824/api/register?id=1";
	//创建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());
	}
}
/// <summary>
/// HttpClient实现Put请求(异步)
/// </summary>
static async void dooPut()
{
	var userId = 1;
	string url = "http://localhost:52824/api/register?userid=" + userId;

	//设置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>()       
		{
		   {"Name","修改zzl"},
		   {"Info", "Put修改动作"}//键名必须为空
		});

		//await异步等待回应

		var response = await http.PutAsync(url, content);
		//确保HTTP成功状态值
		response.EnsureSuccessStatusCode();
		//await异步读取最后的JSON(注意此时gzip已经被自动解压缩了,因为上面的AutomaticDecompression = DecompressionMethods.GZip)
		Console.WriteLine(await response.Content.ReadAsStringAsync());
	}
}

转载于:https://my.oschina.net/smartsmile/blog/815103

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值