2013-11-22 30 views
0

如果我看看小提琴手請求使用該System.Text.Encoding.UTF8.GetBytes引入怪異字符

using System; 
using System.IO; 
using System.Net; 

class Test 
{ 
    static void Main() 
    { 
     string xml = "<xml>...</xml>"; 
     byte[] arr = System.Text.Encoding.UTF8.GetBytes(xml); 
     HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("http://localhost/"); 
     request.Method = "PUT"; 
     request.ContentType = "text/xml"; 
     request.ContentLength = arr.Length; 
     Stream dataStream = request.GetRequestStream(); 
     dataStream.Write(arr, 0, arr.Length); 
     dataStream.Close(); 
     HttpWebResponse response = (HttpWebResponse)request.GetResponse(); 
     string returnString = response.StatusCode.ToString(); 
     Console.WriteLine(returnString); 
    } 
} 

this SO answer

禮貌有一個執行PUT到客戶端的Web服務奇怪的字符在我的後期請求</xml>看起來像一個正方形[懷疑其一個BOM]

不知道它是如何引入我的我的字符串。

+0

默認的'UTF8.GetBytes'不包含BOM,如果你問一個,它將被添加到數組的前端而不是結束。您發佈的代碼在我的測試中不包含「奇怪的字符」,所以其他事情正在發生。你還在做其他任何事情嗎?複製「奇怪的字符」並在十六進制編輯器中查看它。 –

+0

如何創建xml字符串?例如,如果你使用的是XmlWriter,那麼你需要像這樣設置:'new XmlWriterSettings {Encoding = new UTF8Encoding(false)}' – Jaex

回答

2

使用new UTF8Encoding(false).GetBytes(xml);

UTF8Encoding Constructor (Boolean):初始化UTF8Encoding類的新實例。一個參數指定是否提供Unicode字節順序標記。

+0

嘗試過,但奇怪的方塊仍然存在於我的xml數據在fiddler末尾。 – user1361914