由於本文並非WinCE開發普及篇,所以一些WinCE開發和WCF開發的基礎還請移步百度和谷歌尋找答案,然後結合本文開發出WinCE中如何訪問WCF,謝謝。
開發環境
IDE:Visual Studio 2008 (2010、2012、2013目前都不支持)
OS:Win 7 (64位)
Tools:ActiveSync win7 v6.1(設備中心,給Pocket PC 2003模擬器提供網絡)
模擬器網絡連接攻略一份:http://www.jb51.net/softjc/42088.html
創建WinCE項目
請恕本文並非WinCE開發普及篇,所以這些請百度吧。
WCF服務端
app.config中關鍵代碼
<service behaviorConfiguration="SystemDispatchServiceForPDABehavior" name="SystemManageServiceLibrary.SystemDispatchServiceForPDA"> <!--PDA系統分配--> <endpoint address="http://localhost:20003/SystemDispatchForPDA/SystemDispatchServiceForPDA" binding="webHttpBinding" contract="SystemManageServiceLibrary.SystemDispatch.ISystemDispatchServiceForPDA" > </endpoint> <!--PDA系統分配元數據--> <endpoint address="http://localhost:20003/SystemDispatchForPDA/SystemDispatchServiceForPDA/mex" binding="mexHttpBinding" contract="IMetadataExchange" /> <host> <baseAddresses> <add baseAddress="http://localhost:20003/SystemDispatchForPDA"/> </baseAddresses> <timeouts openTimeout="00:00:30" /> </host> </service> View Code服務契約 - 公布WCF REST(詳細的可以百度搜索 WCF REST)
[ServiceContract] public interface ISystemDispatchServiceForPDA { /// <summary> /// PDA獲取集群信息 /// </summary> /// <param name="strPDA_IMEI">PDA內部出廠序號</param> /// <returns></returns> [OperationContract] //UriTemplate 實際就是通過http協議發送請求的url規則,把{strPDA_IMEI}替換成真實的PDA串號即可 [WebGet(UriTemplate = "GetClusterInfo/{strPDA_IMEI}")] CLUSTER GetClusterInfo(string strPDA_IMEI); } View Code
WinCE
HttpWrapper.cs - Http請求的封裝,訪問WCF提供的REST服務
public class HttpWrapper { public static string SendRequest(string url) { HttpWebResponse response = null; HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest; request.Method = "GET"; request.AllowWriteStreamBuffering = false; request.KeepAlive = true; request.ContentType = "application/x-www-form-urlencoded"; // 接收返回的頁面 response = request.GetResponse() as HttpWebResponse; Stream responseStream = response.GetResponseStream(); StreamReader reader = new System.IO.StreamReader(responseStream, Encoding.UTF8); string strResult = reader.ReadToEnd(); reader.Close(); response.Close(); return strResult; } } View CodeXmlAdapter.cs - Xml適配器,用於將Xml轉換成類
public class XmlAdapter { public static T ConvertToClass<T>(string strXML) where T : class { XmlSerializer xmlSerializer = new XmlSerializer(typeof(T)); MemoryStream reader = new MemoryStream(Encoding.UTF8.GetBytes(strXML)); T obj = xmlSerializer.Deserialize(reader) as T; reader.Dispose(); return obj; } } View Code調用方法
private static string URL = "http://ip:20003/SystemDispatchForPDA/SystemDispatchServiceForPDA/"; public static CLUSTER GetClusterInfo(string strPDA_IMEI) { string strResponse = HttpWrapper.SendRequest(URL + "GetClusterInfo/" + strPDA_IMEI); CLUSTER cluster = XmlAdapter.ConvertToClass<CLUSTER>(strResponse); return cluster; }
真正需要注意的其實就是幾點:
1.安裝設備中心
2.設置模擬器網絡連接
3.WCF REST
4.WinCE解析WCF返回的XML,以及如何拼接訪問的URL