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

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

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

NeverSettle101   2021-09-10 我要评论
想了解C#通过HttpWebRequest发送带有JSON Body的POST请求实现的相关内容吗,NeverSettle101在本文为您仔细讲解C# post请求 HttpWebRequest的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:C#,post请求,HttpWebRequest,C#,HttpWebRequest,JSON,post,下面大家一起来学习吧。

起因

很多博客都有描述到这个问题,那么为什么我还要写一篇文章来说一下呢,因为其他的都似乎已经过时了,会导致其实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 数据。

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们