2013年9月26日 星期四

[ASP.NET]C#發送XML Request至PHP頁面

需求概述
專案上常常有與公司夥伴的系統做一些資料的交換,在以往我遇過的都是使用.NET 的Web Service走SOAP協定來做,但這次拿到的規格書是要走HTTP POST的方式,並義好XML架構,在加上一些加解密來做異質系統的交換,而對方的系統是用PHP撰寫的,試了好久終於將傳遞與接收完成,趕快紀錄一下 :(

WebRequest XmlRequest = WebRequest.Create("http://xxxxxxx/Service.php");
XmlRequest.Method = "POST";
//XML範例
string XML = @"
    <XML>
        <TEST>
            <eventTime>2013-08-24 08:00:00</eventTime>
        </TEST>
    </XML>";
byte[] byteArray = Encoding.UTF8.GetBytes("temp=" + XML); //temp為參數的名稱
XmlRequest.ContentLength = byteArray.Length;
XmlRequest.ContentType = "application/x-www-form-urlencoded";
Stream RequestStream = XmlRequest.GetRequestStream();
RequestStream.Write(byteArray, 0, byteArray.Length);
RequestStream.Close();
WebResponse response = XmlRequest.GetResponse(); //開始實做傳遞
Console.WriteLine(((HttpWebResponse)response).StatusDescription);
RequestStream = response.GetResponseStream();
StreamReader reader = new StreamReader(RequestStream);
string responseFromServer = reader.ReadToEnd(); //解析對方回傳的XML

Reference
http://stackoverflow.com/questions/6995314/how-to-send-an-xml-from-a-c-sharp-desktop-application-to-a-php-server-script-and PHP Receiver http://docs.php.net/wrappers.php.php

沒有留言:

張貼留言