当我在c#中发送这个xml时 - 即使我已指定" UTF-8"它也会以非UTF-8格式发送。在xml文档声明和HttpWebRequest.ContentType中都有。如何强制它以UTF-8发送数据?
XmlDocument xmlDoc = new XmlDocument();
XmlDeclaration xmlDeclaration = xmlDoc.CreateXmlDeclaration("1.0", "UTF-8", null);
XmlElement root = xmlDoc.DocumentElement;
xmlDoc.InsertBefore(xmlDeclaration, root);
XmlElement element1 = xmlDoc.CreateElement(string.Empty, "pacsoft", string.Empty);
xmlDoc.AppendChild(element1);
string destinationUrl = "";
Uri uri = new Uri(destinationUrl);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
byte[] bytes;
bytes = System.Text.Encoding.ASCII.GetBytes(requestXml);
request.ContentType = "text/xml; encoding='utf-8'";
request.ContentLength = bytes.Length;
request.Method = "POST";
Stream requestStream = request.GetRequestStream();
requestStream.Write(bytes, 0, bytes.Length);
requestStream.Close();
HttpWebResponse response;
response = (HttpWebResponse)request.GetResponse();
if (response.StatusCode == HttpStatusCode.OK)
{
Stream responseStream = response.GetResponseStream();
string responseStr = new StreamReader(responseStream, System.Text.Encoding.UTF8).ReadToEnd();
return responseStr;
}
答案 0 :(得分:0)
找到它:我需要将此行更改为:
bytes = System.Text.Encoding.UTF8.GetBytes(requestXml);
答案 1 :(得分:0)
您必须更改一行:
bytes = System.Text.Encoding.ASCII.GetBytes(requestXml);
到
bytes = System.Text.Encoding.UTF8.GetBytes(requestXml)
您在ContentType标头中设置的内容是服务器知道您要接受哪种编码以进行响应。