温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

C#怎么通过HttpWebRequest发送带有JSON Body的POST请求

发布时间:2021-09-10 17:05:06 来源:亿速云 阅读:1187 作者:chen 栏目:开发技术

本篇内容介绍了“C#怎么通过HttpWebRequest发送带有JSON Body的POST请求”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!

目录
  • 原来的处理方式

  • 新的方式

原来的处理方式

通过 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请求”的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识可以关注亿速云网站,小编将为大家输出更多高质量的实用文章!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI