无名阁,只为技术而生。流水不争先,争的是滔滔不绝。

C#WebApI:C#调用Web Api的通用方法

C# dancy 9个月前 (11-30) 187次浏览 已收录 0个评论 扫描二维码
C#WebApI:C#调用Web Api的通用方法

C#WebApI

C#WebApI怎么调用?如何使用程序调用webApi接口?本篇将做详细介绍。

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();
            }
        }
点击展开
喜欢 (0)
[]
分享 (0)
关于作者:
发表我的评论
取消评论

评论审核已启用。您的评论可能需要一段时间后才能被显示。

表情 贴图 加粗 删除线 居中 斜体 签到