Web Service 小练习

     对于网站与网站之间数据互动,这是我的说法,不是专家说的,不要相信。应该有专业的说法。

     从他人的网站通过一个接口获取数据,这一直是我感到神奇的事,怎么实现的,一直萦绕于心,想要弄过究竟,怎么是实现的啊!不止一次在群里听到同样的提问。可惜每次我都没有深入探究,自己太懒惰了,不想动手实践,想找现成的,可惜也没有去找。

     还是要工作压力驱使,不然也许这个一直对我来说是一个疑惑。工作中有这么一个任务就是通过接口去获取供应商的数据,还好已经有现成的了,我只要看懂,然后模仿做一个就可以了,不过也费了我不少时间。发现有两种方式:一是通过xml,二是通过web service。我做的是用xml实现,而另外一种当时就没有深入去探究了。但是在我心里一直是一个结,我要试一试,实现它。于是有了今天的结果。一个小小实验。

   我是用asp.net 4.0实验的 两个项目,模拟两个网站。其实也包含了几个知识点:web Service,数据压缩,流数据等,dataset 与流的互转化。

  web Service 端代码,从数据库中获取数据,然后使用了压缩,流传递数据

  1 using System;
  2 using System.Collections.Generic;
  3 using System.Linq;
  4 using System.Web;
  5 using System.Web.Services;
  6 using System.Data;
  7 using System.Data.SqlClient;
  8 using System.Text;
  9 using System.IO;
 10 using System.Runtime.Serialization.Formatters.Binary;
 11 using System.Runtime.Serialization;
 12 using System.IO.Compression;
 13 
 14 
 15 namespace WebSiteTest
 16 {
 17     /// <summary>
 18     /// WebServiceSend 的摘要说明
 19     /// </summary>
 20     [WebService(Namespace = "http://tempuri.org/")]
 21     [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
 22     [System.ComponentModel.ToolboxItem(false)]
 23     // 若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务,请取消对下行的注释。
 24     // [System.Web.Script.Services.ScriptService]
 25     public class WebServiceSend : System.Web.Services.WebService
 26     {
 27 
 28         [WebMethod]
 29         public string HelloWorld()
 30         {
 31             return "Hello World";
 32         }
 33 
 34         [WebMethod]
 35         public int add( int a, int b) 
 36         {
 37             return a + b;
 38         }
 39 
 40         //用流发送数据
 41         [WebMethod]
 42         public byte[] getdata(int id)
 43         {
 44             byte[] bArrayResult = null;
 45             string sqlstr = "select * from   BlogArticle where BlogId>" + id;
 46             DataSet ds=new DataSet();
 47             using (SqlConnection conn = new SqlConnection(connstr))
 48             {
 49                 conn.Open();
 50                 using (SqlCommand cmd = new SqlCommand())
 51                 {
 52                     cmd.CommandText = sqlstr;
 53                     cmd.CommandType = CommandType.Text;
 54                     cmd.Connection = conn;
 55                     SqlDataAdapter dap = new SqlDataAdapter(cmd);
 56                     dap.Fill(ds);
 57                     ds.RemotingFormat = SerializationFormat.Binary;
 58                     MemoryStream ms = new MemoryStream();
 59                     IFormatter bf = new BinaryFormatter();
 60                     bf.Serialize(ms, ds);
 61                     bArrayResult = ms.ToArray();
 62                     ms.Close();
 63                     return Compress(bArrayResult);
 64                     //return dt.Rows[0]["BlogTitle"].ToString();
 65                 }
 66             }
 67 
 68         }
 69 
 70         //[WebMethod]
 71         //public byte[] getgzipdata(int id)
 72         //{
 73         //    byte[] bArrayResult = null;
 74         //    string sqlstr = "select * from   BlogArticle where BlogId>" + id;
 75         //    DataSet ds = new DataSet();
 76         //    using (SqlConnection conn = new SqlConnection(connstr))
 77         //    {
 78         //        conn.Open();
 79         //        using (SqlCommand cmd = new SqlCommand())
 80         //        {
 81         //            cmd.CommandText = sqlstr;
 82         //            cmd.CommandType = CommandType.Text;
 83         //            cmd.Connection = conn;
 84         //            SqlDataAdapter dap = new SqlDataAdapter(cmd);
 85         //            dap.Fill(ds);
 86         //            ds.RemotingFormat = SerializationFormat.Binary;
 87                  
 88         //            MemoryStream ms = new MemoryStream();
 89         //            IFormatter bf = new BinaryFormatter();
 90         //            bf.Serialize(ms, ds);
 91         //            bArrayResult = ms.ToArray();
 92         //            ms.Close();
 93         //            return bArrayResult;
 94         //            //return dt.Rows[0]["BlogTitle"].ToString();
 95         //        }
 96         //    }
 97         //}
 98         //压缩流数据
 99         public static byte[] Compress(byte[] bytes)
100         {
101             using (MemoryStream ms = new MemoryStream())
102             {
103                 GZipStream Compress = new GZipStream(ms, CompressionMode.Compress);
104 
105                 Compress.Write(bytes, 0, bytes.Length);
106 
107                 Compress.Close();
108 
109                 return ms.ToArray();
110 
111             }
112         }
113         private static string connstr = "Data Source=.;Initial Catalog=mytest;Integrated Security=True";//数据库连接
114        
115     }
116 }

 压缩前数据大小如图片一

 压缩后数据大小如图片二

   接收端 代码,需要web引用

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO.Compression;


namespace WebReceivetest
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void btntest_Click(object sender, EventArgs e)
        {
            MyWebTest.WebServiceSend websend = new MyWebTest.WebServiceSend();
            int first = int.Parse(txtfirst.Text);
            int second = int.Parse(txtsecond.Text);
            int result = websend.add(first, second);
            labresult.Text = result.ToString();
            //string xx=websend.getdata(10);
            //labresult.Text = result.ToString() + "-----------" + xx;
            DataSet ds = BinaryToDataset(websend.getdata(151));//151是数据库中的一个id编号
            GridView1.DataSource = ds;
            GridView1.DataBind();
                
        }
        //流转换为dataset数据
        public DataSet BinaryToDataset(byte[] bUserData)
        {
            if (bUserData == null)
            {
                //MessageBox.Show("二进制数据流为空");
                //err = "";
                return null;
            }
            // 反序列化的过程
            MemoryStream ms = new MemoryStream(Decompress(bUserData));
            IFormatter bf = new BinaryFormatter();
            object obj = bf.Deserialize(ms);
            DataSet dsResult = (DataSet)obj;
            ms.Close();
            return dsResult;
        }

        //解压流数据
        public static byte[] Decompress(Byte[] bytes)
        {
            using (MemoryStream tempMs = new MemoryStream())
            {
                using (MemoryStream ms = new MemoryStream(bytes))
                {
                    GZipStream Decompress = new GZipStream(ms, CompressionMode.Decompress);

                    Decompress.CopyTo(tempMs);

                    Decompress.Close();

                    return tempMs.ToArray();
                }
            }
        }
    }
}

解压前数据大小如图片三

 压缩后数据大小如图片四

 

 通过这一次小实验,心中的疑惑完全消除了。实践——求真——消除疑惑。

参考:http://www.cnblogs.com/zhangzheny/archive/2007/06/16/785734.html

http://www.cnblogs.com/amylis_chen/archive/2012/11/06/2757808.html

http://www.cnblogs.com/qugangf/archive/2011/04/11/2012193.html

原文地址:https://www.cnblogs.com/annabook/p/4821542.html