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

本文主要介绍了C#通过HttpWebRequest发送带有JSON Body的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 数据。

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

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

基础教程推荐