博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
C# 调用WebApi
阅读量:5282 次
发布时间:2019-06-14

本文共 4580 字,大约阅读时间需要 15 分钟。

 

1.WebRequest方式

Post:

private void button1_Click(object sender, EventArgs e)        {           string ss= HttpPost("http://localhost:41558/api/Demo/PostXXX", "{Code:\"test089\",Name:\"test1\"}"); } public static string HttpPost(string url, string body) { //ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult); Encoding encoding = Encoding.UTF8; HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); request.Method = "POST"; request.Accept = "text/html, application/xhtml+xml, */*"; request.ContentType = "application/json"; byte[] buffer = encoding.GetBytes(body); request.ContentLength = buffer.Length; request.GetRequestStream().Write(buffer, 0, buffer.Length); HttpWebResponse response = (HttpWebResponse)request.GetResponse(); using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8)) { return reader.ReadToEnd(); } }

 

Get:

private void button1_Click(object sender, EventArgs e)        {            string ss = HttpGet("http://localhost:41558/api/Demo/GetXXX?Name=北京"); } public static string HttpGet(string url) { //ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult); Encoding encoding = Encoding.UTF8; HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); request.Method = "GET"; request.Accept = "text/html, application/xhtml+xml, */*"; request.ContentType = "application/json"; HttpWebResponse response = (HttpWebResponse)request.GetResponse(); using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8)) { return reader.ReadToEnd(); } }

 

2.HttpClient 方式

Post:

private async void button2_Click(object sender, EventArgs e){     HttpClient client = new HttpClient(); //由HttpClient发出Delete Method HttpResponseMessage response = await client.DeleteAsync("http://localhost:41558/api/Demo"+"/1"); if (response.IsSuccessStatusCode) MessageBox.Show("成功"); } private async void button3_Click(object sender, EventArgs e) { //创建一个处理序列化的DataContractJsonSerializer DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(People)); MemoryStream ms = new MemoryStream(); //将资料写入MemoryStream serializer.WriteObject(ms, new People() { Id = 1, Name = "Hello ni" }); //一定要在这设定Position ms.Position = 0; HttpContent content = new StreamContent(ms);//将MemoryStream转成HttpContent content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json"); HttpClient client = new HttpClient(); //由HttpClient发出Put Method HttpResponseMessage response = await client.PutAsync("http://localhost:41558/api/Demo"+ "/1", content); if (response.IsSuccessStatusCode) MessageBox.Show("成功"); }

Get:

using (WebClient client = new WebClient()){     client.Headers["Type"] = "GET"; client.Headers["Accept"] = "application/json"; client.Encoding = Encoding.UTF8; client.DownloadStringCompleted += (senderobj, es) => { var obj = es.Result; }; client.DownloadStringAsync("http://localhost:41558/api/Demo"); }

 WebAPI接收处理(方法没用参数,不喜欢用参数,反而觉得不好控制)

 

    public class DefaultController : ApiController

    {
        // GET api/values/5
        public List<Site> Get()
        {
            string Name = System.Web.HttpContext.Current.Request["Name"].ToString();

            var sites = new List<Site>();

            sites.Add(new Site { SiteId = 1, Title = "test", Uri = "www.cnblogs.cc" });

            sites.Add(new Site { SiteId = 2, Title = "博客园首页", Uri = "www.cnblogs.com" });

            sites.Add(new Site { SiteId = 3, Title = "博问", Uri = "q.cnblogs.com" });

            sites.Add(new Site { SiteId = 4, Title = "新闻", Uri = "news.cnblogs.com" });

            sites.Add(new Site { SiteId = 5, Title = "招聘", Uri = "job.cnblogs.com" });

            var result = (from Site site in sites where site.SiteId > 0 select site).Take(10).ToList();
            return result;

        }

        // POST api/values

        public List<Site> Post()
        {
           
            System.IO.Stream s = System.Web.HttpContext.Current.Request.InputStream;
            byte[] b = new byte[s.Length];
            s.Read(b, 0, (int)s.Length);
            string Name= System.Text.Encoding.UTF8.GetString(b);

            var sites = new List<Site>();

            sites.Add(new Site { SiteId = 1, Title = "test", Uri = "www.cnblogs.cc" });

            sites.Add(new Site { SiteId = 2, Title = "博客园首页2", Uri = "www.cnblogs.com" });

            sites.Add(new Site { SiteId = 3, Title = "博问", Uri = "q.cnblogs.com" });

            sites.Add(new Site { SiteId = 4, Title = "新闻", Uri = "news.cnblogs.com" });

            sites.Add(new Site { SiteId = 5, Title = "招聘", Uri = "job.cnblogs.com" });

            var result = (from Site site in sites where site.SiteId > 0 select site).Take(10).ToList();
            return result;
        }
    }

 

转载于:https://www.cnblogs.com/cuihongyu3503319/p/9088144.html

你可能感兴趣的文章
查看CPU数量和核心数
查看>>
Android异步加载网络图片
查看>>
python学习之 - XML
查看>>
css问题小计
查看>>
Laravel学习笔记(三)数据库 数据库迁移
查看>>
ORACLE查看并修改最大连接数
查看>>
box-flex不均分问题
查看>>
Python--GIL 详解
查看>>
Oracle数据导入Mysql中
查看>>
BZOJ-4424 &&CodeForces-19E Fairy DP+dfs (Link-Cut-Tree可A)
查看>>
MongoDB学习笔记——聚合操作之group,distinct,count
查看>>
大道至简读后感(第四章)
查看>>
IDA IDC Tutorials: Additional Auto-Commenting
查看>>
k8s-存储卷1-十二
查看>>
在Android中Intent的概念及应用(二)——Intent过滤器相关选项
查看>>
前端面试题(4)iframe有哪些优点?iframe缺点是什么?
查看>>
第十六章 多态性(一)
查看>>
INSERT IGNORE INTO / REPLACE INTO
查看>>
Python数据类型-布尔/数字/字符串/列表/元组/字典/集合
查看>>
类的无参方法
查看>>