iis服务器助手广告广告
返回顶部
首页 > 资讯 > 后端开发 > 其他教程 >C#通过HttpWebRequest发送带有JSON Body的POST请求实现
  • 138
分享到

C#通过HttpWebRequest发送带有JSON Body的POST请求实现

2024-04-02 19:04:59 138人浏览 独家记忆
摘要

目录起因 原来的处理方式 新的方式 起因 很多博客都有描述到这个问题,那么为什么我还要写一篇文章来说一下呢,因为其他的都似乎已经过时了,会导致其实body 并没有发送过去。至于为什

起因

很多博客都有描述到这个问题,那么为什么我还要写一篇文章来说一下呢,因为其他的都似乎已经过时了,会导致其实body 并没有发送过去。至于为什么不使用其他的诸如 HttpClient 之类的,是由于业务需要。

原来的处理方式

通过 GetRequestStream 来获取请求流,后把需要发送的 JSON 数据写入到流中


private T PostDataViaHttpWEBRequest<T>(string baseUrl,
            IReadOnlyDictionary<string, string> headers,
            IReadOnlyDictionary<string, string> urlParas,
            string requestBody=null)
        {
            var resulejson = string.Empty;
            try
            {
                var apiUrl = baseUrl;

                if (urlParas != null)
                    urlParas.ForEach(p =>
                    {
                        if (apiUrl.IndexOf("{" + p.Key + "}") > -1)
                        {
                            apiUrl = apiUrl.Replace("{" + p.Key + "}", p.Value);
                        }
                        else
                        {
                            apiUrl += string.FORMat("{0}{1}={2}", apiUrl.Contains("?") ? "&" : "?", p.Key, p.Value);
                        }
                    }
                );
                
                var req = (HttpWebRequest)WebRequest.Create(apiUrl);
                req.Method = "POST";
                req.ContentType = "application/json"; 
                req.ContentLength = 0;

                if (!requestBody.IsNullOrEmpty())
                {
                    using (var postStream = req.GetRequestStream())
                    {
                        var postData = Encoding.ASCII.GetBytes(requestBody);
                        req.ContentLength = postData.Length;
                        postStream.Write(postData, 0, postData.Length);
                    }
                }

                if (headers != null)
                {
                    if (headers.Keys.Any(p => p.ToLower() == "content-type"))
                        req.ContentType = headers.SingleOrDefault(p => p.Key.ToLower() == "content-type").Value;
                    if (headers.Keys.Any(p => p.ToLower() == "accept"))
                        req.Accept = headers.SingleOrDefault(p => p.Key.ToLower() == "accept").Value;
                }

                var response = (HttpWebResponse)req.GetResponse();

                using(Stream stream = response.GetResponseStream())
                {
                    using (StreamReader reader = new StreamReader(stream, Encoding.GetEncoding("UTF-8")))
                    {
                        resuleJson = reader.ReadToEnd();
                    }
                }
            }
            catch (Exception ex)
            {
                return default(T);
            }
            return JsonConvert.DeserializeObject<T>(resuleJson);
        }

但是会发现,数据一直没有正常发送过去,而且代码还显得比较复杂

新的方式

这里修改一下写入 RequestStream 的方式,使用 StreamWriter 包装一下,然后直接写入需要发送的 Json 数据


private T PostDataViaHttpWebRequest<T>(string baseUrl,
            IReadOnlyDictionary<string, string> headers,
            IReadOnlyDictionary<string, string> urlParas,
            string requestBody=null)
        {
            var resuleJson = string.Empty;
            try
            {
                var apiUrl = baseUrl;

                if (urlParas != null)
                    urlParas.ForEach(p =>
                    {
                        if (apiUrl.IndexOf("{" + p.Key + "}") > -1)
                        {
                            apiUrl = apiUrl.Replace("{" + p.Key + "}", p.Value);
                        }
                        else
                        {
                            apiUrl += string.Format("{0}{1}={2}", apiUrl.Contains("?") ? "&" : "?", p.Key, p.Value);
                        }
                    }
                );
                
                var req = (HttpWebRequest)WebRequest.Create(apiUrl);
                req.Method = "POST";
                req.ContentType = "application/json"; //Defalt

                if (!requestBody.IsNullOrEmpty())
                {
                    using (var postStream = new StreamWriter(req.GetRequestStream()))
                    {
                        postStream.Write(requestBody);
                    }
                }

                if (headers != null)
                {
                    if (headers.Keys.Any(p => p.ToLower() == "content-type"))
                        req.ContentType = headers.SingleOrDefault(p => p.Key.ToLower() == "content-type").Value;
                    if (headers.Keys.Any(p => p.ToLower() == "accept"))
                        req.Accept = headers.SingleOrDefault(p => p.Key.ToLower() == "accept").Value;
                }

                var response = (HttpWebResponse)req.GetResponse();

                using(Stream stream = response.GetResponseStream())
                {
                    using (StreamReader reader = new StreamReader(stream, Encoding.GetEncoding("UTF-8")))
                    {
                        resuleJson = reader.ReadToEnd();
                    }
                }
            }
            catch (Exception ex)
            {
                return default(T);
            }
            return JsonConvert.DeserializeObject<T>(resuleJson);
        }

这样即可正确发送 Json 数据。

到此这篇关于C#通过HttpWebRequest发送带有JSON Body的POST请求实现的文章就介绍到这了,更多相关C# post请求 HttpWebRequest内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!

--结束END--

本文标题: C#通过HttpWebRequest发送带有JSON Body的POST请求实现

本文链接: https://www.lsjlt.com/news/135351.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作