[英]C# HttpWebRequest Content-type not Changing
在C#中,我需要使用HTTP將一些數據發布到Web服務器。 我不斷收到Web服務器返回的錯誤,並在嗅探數據后發現問題是內容類型標頭仍設置為“ text / html”,而未更改為“ application / json; Charset = UTF-8”。 我已經盡力想盡一切辦法阻止它被更改,但是我沒有主意。
這是引起問題的函數:
private string post(string uri, Dictionary<string, dynamic> parameters)
{
//Put parameters into long JSON string
string data = "{";
foreach (KeyValuePair<string, dynamic> item in parameters)
{
if (item.Value.GetType() == typeof(string))
{
data += "\r\n" + item.Key + ": " + "\"" + item.Value + "\"" + ",";
}
else if (item.Value.GetType() == typeof(int))
{
data += "\r\n" + item.Key + ": " + item.Value + ",";
}
}
data = data.TrimEnd(',');
data += "\r\n}";
//Setup web request
HttpWebRequest wr = (HttpWebRequest)WebRequest.Create(Url + uri);
wr.KeepAlive = true;
wr.ContentType = "application/json; charset=UTF-8";
wr.Method = "POST";
wr.ContentLength = data.Length;
//Ignore false certificates for testing/sniffing
wr.ServerCertificateValidationCallback = delegate { return true; };
try
{
using (Stream dataStream = wr.GetRequestStream())
{
//Send request to server
dataStream.Write(Encoding.UTF8.GetBytes(data), 0, data.Length);
}
//Get response from server
WebResponse response = wr.GetResponse();
response.Close();
}
catch (WebException e)
{
MessageBox.Show(e.Message);
}
return "";
}
我遇到問題的原因是因為無論我將其設置為什么,內容類型都將保持為“ text / html”。
提前感謝。
聽起來可能很奇怪,但這對我有用:
((WebRequest)httpWebRequest).ContentType = "application/json";
這將更改內部ContentType
,以更新繼承的內容。
我不確定為什么這行得通,但是我想這與ContentType
是WebRequest
的抽象屬性有關,並且在HttpWebRequest
被覆蓋的錯誤或問題有一些
一個潛在的問題是,您要根據字符串的長度設置內容的長度,但這不一定是要發送的正確長度。 也就是說,您本質上具有:
string data = "whatever goes here."
request.ContentLength = data.Length;
using (var s = request.GetRequestStream())
{
byte[] byteData = Encoding.UTF8.GetBytes(data);
s.Write(byteData, 0, data.Length);
}
如果將字符串編碼為UTF-8會導致超過data.Length
個字節,這將導致問題。 如果您使用非ASCII字符(例如重音符號,非英語語言的符號等),則可能會發生這種情況。 因此,發生的是您的整個字符串未發送。
您需要寫:
string data = "whatever goes here."
byte[] byteData = Encoding.UTF8.GetBytes(data);
request.ContentLength = byteData.Length; // this is the number of bytes you want to send
using (var s = request.GetRequestStream())
{
s.Write(byteData, 0, byteData.Length);
}
就是說,我不明白為什么您的ContentType
屬性設置不正確。 我不能說我曾經見過這種情況。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.