在C#中,我需要使用HTTP向Web服务器POST一些数据。我不断收到Web服务器返回的错误消息,并在查看数据后发现问题是Content-type标头仍然设置为"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"。
提前致谢。
"application/json"
而不是"application/json; charset=UTF-8";
吗? - brainless coder