/// <summary>
/// C# POST 發送XML
/// </summary>
/// <param name="url">目標Url</param>
/// <param name="strPost">要Post的字符串(數據)</param>
/// <returns>服務器響應</returns>private string PostXml(string url, string strPost)
{
string result = string.Empty;
//Our postvars
//ASCIIEncoding.ASCII.GetBytes(string str)
//就是把字符串str按照簡體中文(ASCIIEncoding.ASCII)的編碼方式,
//編碼成 Bytes類型的字節流數組;
// 要注意的這是這個編碼方式,還有內容的Xml內容的編碼方式,如果沒有注意對應會出現文末的錯誤
byte[] buffer = Encoding.UTF8.GetBytes(strPost);
StreamWriter myWriter = null;
//根據url創建HttpWebRequest對象
//Initialisation, we use localhost, change if appliable
HttpWebRequest objRequest = (HttpWebRequest)WebRequest.Create(url);
//Our method is post, otherwise the buffer (postvars) would be useless
objRequest.Method = "POST";
//The length of the buffer (postvars) is used as contentlength.
//Set the content length of the string being posted.
objRequest.ContentLength = buffer.Length;
//We use form contentType, for the postvars.
//Set the content type of the data being posted.
objRequest.ContentType = "text/xml";//提交xml
//objRequest.ContentType = "application/x-www-form-urlencoded";//提交表單
try
{
//We open a stream for writing the postvars
myWriter = new StreamWriter(objRequest.GetRequestStream());
//Now we write, and afterwards, we close. Closing is always important!
myWriter.Write(strPost);
}
catch (Exception e)
{
return e.Message;
}
finally
{
myWriter.Close();
}//讀取服務器返回信息
//Get the response handle, we have no true response yet!
HttpWebResponse objResponse = (HttpWebResponse)objRequest.GetResponse();
//using作為語句,用於定義一個范圍,在此范圍的末尾將釋放對象
using (StreamReader sr = new StreamReader(objResponse.GetResponseStream()))
{
//ReadToEnd適用於小文件的讀取,一次性的返回整個文件
result = sr.ReadToEnd();
sr.Close();
}
return result;
}
背景:
我發送的是encoding='UTF-8'格式的xml字符串,但一開始我使用的是
Encoding.Unicode.GetBytes(strPost)或者Default、ASCII均會提示下面的錯誤,如下圖: 修改字符編碼格式後,成功!所以要根據發送的格式選取合適的方法。1、創建httpWebRequest對象,HttpWebRequest不能直接通過new來創建,只能通過WebRequest.Create(url)的方式來獲得。 WebRequest是獲得一些應用層協議對象的一個統一的入口(工廠模式),它根據參數的協議來確定最終創建的對象類型。