C# 用HTTP協議傳送、接收資料
用HTTP協議傳送、接收資料:
傳送:
/// <summary>
/// post給定的url並獲取返回的資料
/// </summary>
/// <param name="url"></param>
/// <param name="timeout"></param>
/// <returns></returns>
private string GetPostResult(string url, string strXml, int timeout)
{
string result;
try
{
strXml = strXml.Remove(0, strXml.IndexOf("<"));
//將資料以資料流方式提交到閘道器
WebRequest myWebRequest = WebRequest.Create(url);
myWebRequest.Method = "POST";
myWebRequest.Timeout = timeout;
//myWebRequest.ContentType = "application/x-www-form-urlencoded";
byte[] data = Encoding.Unicode.GetBytes(strXml);
myWebRequest.ContentLength = data.Length;
//新增Request.ContentType,否則對方可能無法接收
myWebRequest.ContentType = "text/xml";
myWebRequest.GetRequestStream().Write(data, 0, data.Length);
HttpWebResponse rep2 = (HttpWebResponse)myWebRequest.GetResponse();
//獲取返回的資料
//WebResponse myWebResponse = myWebRequest.GetResponse();
StreamReader sr = new StreamReader(rep2.GetResponseStream());
result = sr.ReadToEnd();
result = result.Replace("/r/n", "");
sr.Close();
}
catch (Exception e)
{
System.Diagnostics.Debug.Print(e.ToString());
result = "error";
}
return result;
}
接收:
XmlDocument xmlDoc = new System.Xml.XmlDocument();
byte[] data = new byte[Request.InputStream.Length];
Request.InputStream.Read(data, 0, (int)Request.InputStream.Length);
string orderXml = Encoding.Unicode.GetString(data);
Request.InputStream.Close();
orderXml = Server.HtmlDecode(orderXml);
xmlDoc.LoadXml(orderXml);