C#通過HttpWebRequest發(fā)送帶有JSON Body的POST請(qǐng)求實(shí)現(xiàn)
起因
很多博客都有描述到這個(gè)問題,那么為什么我還要寫一篇文章來說一下呢,因?yàn)槠渌亩妓坪跻呀?jīng)過時(shí)了,會(huì)導(dǎo)致其實(shí)body 并沒有發(fā)送過去。至于為什么不使用其他的諸如 HttpClient 之類的,是由于業(yè)務(wù)需要。
原來的處理方式
通過 GetRequestStream 來獲取請(qǐng)求流,后把需要發(fā)送的 Json 數(shù)據(jù)寫入到流中
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);
}
但是會(huì)發(fā)現(xiàn),數(shù)據(jù)一直沒有正常發(fā)送過去,而且代碼還顯得比較復(fù)雜
新的方式
這里修改一下寫入 RequestStream 的方式,使用 StreamWriter 包裝一下,然后直接寫入需要發(fā)送的 Json 數(shù)據(jù)
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);
}
這樣即可正確發(fā)送 Json 數(shù)據(jù)。
到此這篇關(guān)于C#通過HttpWebRequest發(fā)送帶有JSON Body的POST請(qǐng)求實(shí)現(xiàn)的文章就介紹到這了,更多相關(guān)C# post請(qǐng)求 HttpWebRequest內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
c#實(shí)現(xiàn)輸出的字符靠右對(duì)齊的示例
下面小編就為大家分享一篇c#實(shí)現(xiàn)輸出的字符靠右對(duì)齊的示例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2017-12-12
基于WPF實(shí)現(xiàn)ListBox拖動(dòng)子項(xiàng)
這篇文章主要為大家詳細(xì)介紹了如何基于WPF實(shí)現(xiàn)ListBox拖動(dòng)子項(xiàng)效果,文中的示例代碼講解詳細(xì),具有一定的借鑒價(jià)值,有需要的小伙伴可以參考下2024-04-04
c#基于WinForm的Socket實(shí)現(xiàn)簡(jiǎn)單的聊天室 IM
這篇文章主要介紹了c#基于WinForm的Socket實(shí)現(xiàn)簡(jiǎn)單的聊天室 IM的步驟,幫助大家更好的理解和學(xué)習(xí)使用c#,感興趣的朋友可以了解下2021-05-05
Unity中的靜態(tài)批處理和動(dòng)態(tài)批處理操作
這篇文章主要介紹了Unity中的靜態(tài)批處理和動(dòng)態(tài)批處理操作,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2021-04-04
WinForm項(xiàng)目開發(fā)中NPOI用法實(shí)例解析
這篇文章主要介紹了WinForm項(xiàng)目開發(fā)中NPOI用法,有一定的實(shí)用價(jià)值,需要的朋友可以參考下2014-08-08
C# double和decimal數(shù)據(jù)類型以截?cái)嗟姆绞奖A糁付ǖ男?shù)位數(shù)
從事ASP.NET in C#開發(fā)快一年了,今天才知道,C#中保留小數(shù)位數(shù)時(shí)沒有使用截?cái)嗟姆绞?/div> 2012-05-05
c# 在windows中操作IIS設(shè)置FTP服務(wù)器的示例
這篇文章主要介紹了c# 在windows中操作IIS設(shè)置FTP服務(wù)器的示例,幫助大家更好的理解和學(xué)習(xí)使用c#,感興趣的朋友可以了解下2021-03-03最新評(píng)論

