ASP.NET 使用Get方式请求WebService,并得到DataSet结果
注意:如下使用了如下webservices的配置,将导致客户端引用时将无法引用到ArrayOfInt或ArrayOfString参数。
WebService有多种方式进行请求,如Get,Post,Soap,Documentation等等,注意要使用时在web.config中的system.web节点中增加类似如下的配置节点信息
<webServices> <protocols> <add name="HttpGet"/> <add name="HttpPost"/> <add name="HttpSoap"/> <add name="Documentation"/> <add name="HttpPostLocalhost"/> </protocols> </webServices>
在WebService类中实现了如下方法,分别是返回byte[]和XmlDocument对象
[WebMethod(Description = "返回byte数据")] public byte[] GetKeywordQueueToByteArray(string username, string clientId, string seType, string batchTotal, string maxPage) { DataSet ds = InitData(); ds.DataSetName = "KeywordQueue"; byte[] bytes = DataSetToByte(ds); //返回前可压缩,节省流量 return bytes; } [WebMethod(Description = "返回XmlDocument")] public XmlDocument GetKeywordQueueToXml(string username, string clientId, string seType, int batchTotal, int maxPage) { XmlDocument xd = new XmlDocument(); DataSet ds = InitData(); ds.DataSetName = "KeywordQueue"; xd.LoadXml(ds.GetXml()); return xd; } private DataSet InitData() { DataSet dataset = new DataSet(); DataTable dtKeyword = new DataTable(); dtKeyword.TableName = "keywords"; dtKeyword.Columns.AddRange(new DataColumn[]{ new DataColumn() { ColumnName = "keyword", DataType = typeof(System.String) }, new DataColumn() { ColumnName = "setype", DataType = typeof(System.String) }, new DataColumn() { ColumnName = "maxpage", DataType = typeof(System.Int32) } }); DataTable dtSeType = new DataTable(); dtSeType.TableName = "se"; dtSeType.Columns.AddRange(new DataColumn[]{ new DataColumn() { ColumnName = "code", DataType = typeof(System.String) }, new DataColumn() { ColumnName = "name", DataType = typeof(System.String) }, new DataColumn() { ColumnName = "url", DataType = typeof(System.String) } }); dtKeyword.Rows.Add("手机", "BD", 1); dtKeyword.Rows.Add("网络游戏", "BD", 1); dtSeType.Rows.Add("BD", "百度", ""); dtSeType.Rows.Add("GG", "GG", ""); dataset.Tables.Add(dtKeyword); dataset.Tables.Add(dtSeType); return dataset; } /// <summary> /// 把DateSet转化成byte /// </summary> /// <param name="m_ds"></param> /// <returns></returns> public byte[] DataSetToByte(DataSet dataset) { byte[] result = null; MemoryStream memStream = new MemoryStream(); IFormatter m_formatter = new BinaryFormatter(); dataset.RemotingFormat = SerializationFormat.Binary; MemoryStream ms = new MemoryStream(); IFormatter bf = new BinaryFormatter(); bf.Serialize(ms, dataset); result = ms.ToArray(); ms.Close(); return result; }
请求WebService的测试方法
public static void Invoke() { //string webserviceUrl = "http://localhost:9090/KeywordQueueService.asmx/HelloWorld?content=hello world"; Console.WriteLine("WebService返回XmlDocument,直接解析为DataSet"); GetDataSetFromWebServiceByXmlDocument(); Console.WriteLine("WebService返回byte[],直接解析为DataSet"); GetDataSetFromWebServiceByteArray(); } /// <summary> /// WebService返回的是Byte数组 /// </summary> static void GetDataSetFromWebServiceByteArray() { string webserviceUrl = "http://localhost:9090/KeywordQueueService.asmx/GetKeywordQueueToByteArray?username=test1&clientId=dkkad8789adda&seType=BD&batchTotal=61&maxPage=1"; string charSet = "utf-8"; try { string pageContent = GetWebServiceContent(webserviceUrl, charSet); Console.WriteLine(pageContent); //加载文档 XmlDocument xd = new XmlDocument(); xd.LoadXml(pageContent); byte[] bytes = Convert.FromBase64String(xd.DocumentElement.InnerText); //因为WebService方法中序列化过,所以这里需要反序列化 MemoryStream ms = new MemoryStream(bytes); System.Runtime.Serialization.IFormatter bf = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter(); object obj = bf.Deserialize(ms); DataSet dataset = obj as DataSet; ms.Close(); } catch (Exception err) { Console.WriteLine(err.ToString()); } } /// <summary> /// WebService返回的是XmlDocument /// </summary> static void GetDataSetFromWebServiceByXmlDocument() { string webserviceUrl = "http://localhost:9090/KeywordQueueService.asmx/GetKeywordQueueToXml?username=test1&clientId=dkkad8789adda&seType=BD&batchTotal=61&maxPage=1"; string charSet = "utf-8"; try { string pageContent = GetWebServiceContent(webserviceUrl, charSet); Console.WriteLine(pageContent); XmlDocument xd = new XmlDocument(); xd.LoadXml(pageContent); DataSet ds = new DataSet(); ds.ReadXml(new XmlNodeReader(xd)); } catch (Exception err) { Console.WriteLine(err.ToString()); } } /// <summary> /// 请求WebService /// </summary> /// <param name="webserviceUrl"></param> /// <param name="charset"></param> /// <returns></returns> static string GetWebServiceContent(string webserviceUrl, string charset) { HttpWebRequest request = (HttpWebRequest)WebRequest.Create(webserviceUrl); request.Method = "GET"; request.Timeout = 60000; HttpWebResponse response = request.GetResponse() as HttpWebResponse; Stream streamReceive = response.GetResponseStream(); Encoding encoding = Encoding.Default; if (!string.IsNullOrEmpty(charset) && Encoding.GetEncoding(charset) != Encoding.Default) { encoding = Encoding.GetEncoding(charset); } StreamReader streamReader = new StreamReader(streamReceive, encoding); return streamReader.ReadToEnd(); } /// <summary> /// 将Byte[]转换为DataSet /// <para>反序列化了一下</para> /// </summary> /// <param name="data"></param> /// <returns></returns> static DataSet GetDataSetByUnCompressByte(byte[] data) { MemoryStream ms = new MemoryStream(data); System.Runtime.Serialization.IFormatter bf = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter(); object obj = bf.Deserialize(ms); DataSet dsResult = (DataSet)obj; ms.Close(); return dsResult; }
注意,如果数据量极少时,直接返回XmlDocument占用流量更小,如果数据量稍大,则使用压缩的byte[]方式更节省流量!
posted on 2012-12-17 15:08 blackcore 阅读(6070) 评论(0) 编辑 收藏 举报