html调用webapi绘图,使用HttpClient调用WebAPI接口,含WebAPI端示例

本文介绍了如何使用 C# 的 HttpClient 进行不同类型的 HTTP 请求,包括原始方式调用、多参数传递、上传图片,并展示了PostAsJsonAsync方法的应用。同时涵盖了客户端与服务器交互的关键操作。
摘要由CSDN通过智能技术生成

usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Web;usingSystem.Web.Mvc;usingSystem.Net.Http;usingSystem.Text;usingSystem.Net.Http.Headers;usingSystem.IO;usingNewtonsoft.Json;namespaceWebApi.Controllers

{public classClientController : Controller

{//GET: Client

publicActionResult Index()

{//HttpClient client = new HttpClient();//string Url = "http://localhost:33495/api/default/";

#region 原始方式调用

//StringContent方式调用//var result = client.PostAsync(Url, new StringContent("111", Encoding.UTF8, "application/json")).Result;//ByteArrayContent方式//var data = Encoding.UTF8.GetBytes("\"ddd\"");//data = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(new menu { menuId = 1, menuName = "33333" }));//data = Encoding.UTF8.GetBytes("{menuId:1,menuName:333}");//var content = new ByteArrayContent(data);//content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json");//var result_byte = client.PostAsync(Url, content).Result;//PostAsJsonAsync方式//client.PostAsJsonAsync(Url, "ss");

#endregion

#region 多参数传参

//client.PutAsJsonAsync(string.Format("{0}{1}?guid={2}", Url, 5, Guid.NewGuid()), "test");

#endregion

#region 服务端上传图片

//服务端上传图片//using (HttpClient client = new HttpClient())//{//var content = new MultipartFormDataContent();// //添加字符串参数,参数名为qq//content.Add(new StringContent("123456"), "qq");//string path = Server.MapPath("/Images/test.jpg");// //添加文件参数,参数名为files,文件名为123.png//content.Add(new ByteArrayContent(System.IO.File.ReadAllBytes(path)), "file", "test.jpg");//var requestUri = "http://localhost:33495/api/default/";//var result = client.PostAsync(requestUri, content).Result.Content.ReadAsStringAsync().Result;//Response.Write(result);//}

#endregion

return null;

}publicActionResult HTML()

{returnView();

}publicActionResult Upload()

{returnView();

}

}

}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值