您好,登錄后才能下訂單哦!
本篇內容介紹了“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請求”的內容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業相關的知識可以關注億速云網站,小編將為大家輸出更多高質量的實用文章!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。