How to send POST request with JSON Body through HttpWebRequest
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!