Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to send POST request with JSON Body through HttpWebRequest

2025-01-31 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article introduces the knowledge of "how C # sends POST requests with JSON Body through HttpWebRequest". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

Catalogue

The original way of handling

A new way

The original way of handling

Obtain the request flow through GetRequestStream, and then write the Json data to be sent to the stream

Private T PostDataViaHttpWebRequest (string baseUrl, IReadOnlyDictionary headers, IReadOnlyDictionary 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 (resuleJson);}

But you will find that the data has not been sent normally, and the code is quite complex.

A new way

Here, modify the way you write to RequestStream, wrap it with StreamWriter, and then write the Json data to be sent directly.

Private T PostDataViaHttpWebRequest (string baseUrl, IReadOnlyDictionary headers, IReadOnlyDictionary 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 (resuleJson);}

This allows the Json data to be sent correctly.

This is the end of the content of "how to send a POST request with JSON Body through HttpWebRequest". Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report