WebService讲解

一、名词解释

  Web Service  【服务供应商

  SOAP--(Simple Object Access Protocal )简单对象访问协议,在分散或分布式环境中交换信息的简单协议。【两个公司之间签的合同,约束双方按照一定的规范和标准做事

  WSDL--(Web Service Description Language)Web Service描述语言,即说明文档。【说明书,告诉别人你有什么,能给别人什么服务

  UDDI --( ) 通用发现、说明和集成,是web服务的黄页。【好比你的公司需要在黄页或工商注册,方便别人查询

二、WebService的高级应用

2.1、Asp.net中调用WS(get方式)

string strURL = "http://localhost:21695/Service1.asmx/GetExtOAAddressInfoByDeptId?deptId=1"; 
            //创建一个HTTP请求
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(strURL);
            //request.Method="get";
            HttpWebResponse response = (System.Net.HttpWebResponse)request.GetResponse();
            Stream s = response.GetResponseStream();
            XmlTextReader Reader = new XmlTextReader(s);
            Reader.MoveToContent();
            string strValue = Reader.ReadInnerXml();
            strValue = strValue.Replace("&lt;", "<");
            strValue = strValue.Replace("&gt;", ">");
            Regex rx = new Regex(@"(\r\n)+");
            strValue = rx.Replace(strValue, "");
                 div1.InnerHtml = strValue;
            Reader.Close();
View Code

2.2、Asp.net中调用WS(post方式)

string strURL = "http://localhost:21695/Service1.asmx/GetExtOAAddressInfoByDeptId";
            //创建一个HTTP请求
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(strURL);
            //Post请求方式
            request.Method = "POST";
            //内容类型
            request.ContentType = "application/x-www-form-urlencoded";
            //参数经过URL编码
            string paraUrlCoded = HttpUtility.UrlEncode("deptId");
            paraUrlCoded += "=" + HttpUtility.UrlEncode(this.txtUserId.Text);
            byte[] payload;
            //将URL编码后的字符串转化为字节
            payload = System.Text.Encoding.UTF8.GetBytes(paraUrlCoded);
            //设置请求的ContentLength 
            request.ContentLength = payload.Length;
 //获得请求流
            Stream writer = request.GetRequestStream();
            //将请求参数写入流
            writer.Write(payload, 0, payload.Length);
            //关闭请求流
            writer.Close();
            //获得响应流
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream s = response.GetResponseStream();
            XmlTextReader Reader = new XmlTextReader(s);
            Reader.MoveToContent();
            string strValue = Reader.ReadInnerXml();
            strValue = strValue.Replace("&lt;", "<");
            strValue = strValue.Replace("&gt;", ">");
            Regex rx=new Regex(@"(\r\n)+"); 
            strValue=rx.Replace(strValue,"");
            this.ClientScript.RegisterStartupScript(typeof(string), null, "alert('" + strValue + "')", true);
            Reader.Close();
View Code

  WebService所在的web.config中的小细节:

<webServices>
      <protocols>
        <add name="HttpPost" />
        <add name="HttpGet" />
      </protocols>
  </webServices>
View Code

2.3、JS同步调用WS

WebService接口:
        /// <summary>
        /// 根据部门ID得到该部门的通讯录
        /// </summary>
        /// <param name="deptId">部门ID</param>
        /// <returns></returns>
        [WebMethod(Description = "根据部门ID得到该部门的通讯录")]
        public string GetExtOAAddressInfoByDeptId(int deptId)
        {
            string sql = @"select a.Id,a.UserName,b.DutyName,a.Mobile,a.QQ,a.Email from 
                            UserInfo a inner Join DutyInfo b
                            on a.DutyInfoNo=b.Id where deptInfoNo=" + deptId;
            DataSet ds = DBHelper.GetDataSet(sql);
            ds.DataSetName = "ExtOA";
            return ds.GetXml();
        }
/// <summary>
        /// 得到某个员工某个月份的工单得分
        /// </summary>
        /// <param name="year"></param>
        /// <param name="month"></param>
        /// <param name="userId"></param>
        /// <returns>工单得分:-1代表出错</returns>
        [WebMethod(Description = "得到某个员工某个月份的工单得分")]
        public int GetWorkAssessScore(int year, int month, string userId)
        {
            string sql = string.Format(@"select WorkAssessScore from dbo.WorkAssess
                            where WorkerStateNo=5 and AcceptWorkAssesserNo={0}
                            and year(WorkAssessPublishDate)={1}
                            and month(WorkAssessPublishDate)={2}", userId, year, month);
            int score = DBHelper.GetScalar(sql);
            return score;
        }
var htmls =[];
        htmls.push("<table border='1' width=300>");
        var header="<tr><th>姓名</th><th>手机号</th></tr>";
        htmls.push(header);
        for (var i = 0; i < userNames.length; i++) { 
           htmls.push("<tr>");
           htmls.push("<td>"+userNames[i]+"</td>"+"<td>"+mobiles[i]+"</td>");
           htmls.push("</tr>");
        }
        htmls.push("</table>");
        div1.innerHTML=htmls.join("");
    }
 function getWorkAssScore() {
        docSubmit = new ActiveXObject("Microsoft.XMLDOM");
        docSubmit.async = false;
        docSubmit.load("http://localhost:21695/Service1.asmx/GetWorkAssessScore?year=2010&month=10&userid=2");
        alert(docSubmit.documentElement.text);
        var s = docSubmit.documentElement.text; //获取返回结果
        result.innerHTML = s;
    } 
View Code

2.4、JS post方式同步调用WS

function GetData_HTTPPOST(i) {
        var URL = "http://localhost:21695/Service1.asmx/GetExtOAAddressInfoByDeptId";
        var Params = "deptId=" + i; // Set postback parameters
        var xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        xmlhttp.Open("POST", URL, false);
        xmlhttp.SetRequestHeader("Content-Type", "application/x-www-form-urlencoded");
        xmlhttp.SetRequestHeader("Content-Length", Params.length);
        xmlhttp.send(Params);
        var doc = xmlhttp.responseXML;
        //div1.innerHTML = x.childNodes[1].text;

        alert(doc.documentElement.text);

        //返回调用状态,状态为200说明调用成功,500则说明出错
        alert(xmlhttp.Status);
        alert(xmlhttp.StatusText);
    } 
View Code

2.5、JS post方式异步调用WS

//Post异步调用
    function GetData_HTTPPOSTASYN(i) {
        var URL = "http://localhost:21695/Service1.asmx/GetExtOAAddressInfoByDeptId";
        var Params = "deptId=" + i; // Set postback parameters
        var xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        xmlhttp.Open("POST", URL, true);
        xmlhttp.SetRequestHeader("Content-Type", "application/x-www-form-urlencoded");
        xmlhttp.SetRequestHeader("Content-Length", Params.length);
        xmlhttp.onreadystatechange = function() {
            if (xmlhttp.readyState == 4 && xmlhttp.Status == 200) {
                var docSubmit = xmlhttp.responseXML;
                docSubmit.loadXML(docSubmit.xml.replace(/&lt;/g, "<").replace(/&gt;/g, ">"));
                 …
}
         xmlhttp.send(Params);
View Code

三、WebService的高级应用2

3.1、 利用WS上传图片/文件

  web service端 

    [WebMethod(Description = "下?载?文?件t.")]  
    public byte[] GetBinaryFile(string filename)  
    {     
         if (File.Exists(filename))     
         {       
             try       
             {         
                 FileStream s = File.OpenRead(filename);         
                 return ConvertFileToByteBuffer(s);       
             }       
             catch (Exception e)       
             {          
                 return new byte[0];       
             }    
         }else    
         {       
             return new byte[0];    
         }  
     }
/// <summary> 
    ///把给定的文件流转换为二进制字节数组
    /// summary> 
    /// <param name="theStream"></param> 
    /// <returns></returns> 
    public byte[] ConvertFileToByteBuffer(System.IO.Stream theStream)  
    {     
        int b1;     
        System.IO.MemoryStream tempStream = new System.IO.MemoryStream( );     
        while ((b1 = theStream.ReadByte( )) != -1)     
        {       
            tempStream.WriteByte(((byte)b1));     
        }     
        return tempStream.ToArray( );  
    } 
View Code

  调用端

protected void btnDown_Click(object sender, EventArgs e)
    {
        if (this.ListBox1.SelectedValue == "") 
        { 
            Response.Write("<script>alert('请选择要下载的图片!');location='Default.aspx'script>"); return; 
        }    
        //获取文件后缀名     
        string lastname = this.ListBox1.SelectedValue.Substring(this.ListBox1.SelectedValue.LastIndexOf('.'));    
        //获取所选文件的服务器路径     
        string serverpath = Server.MapPath("File/" +this.ListBox1.SelectedValue);     
        // 在此处放置用户代码以初始化页面     
        //定义并初始化文件对象     
        localhost.Service oImage = new localhost.Service(); 
        //得到二进制文件字节数组     
        byte[] image = oImage.GetBinaryFile(serverpath);          
        //转换为支持存储区为内存的流          
        System.IO.MemoryStream memStream = new System.IO.MemoryStream(image);          
//定义并实例化Bitmap对象          
        Bitmap bm = new Bitmap(memStream);          
        //根据不同的条件进行输出或者下载          
        Response.Clear( );          
        //如果请求字符串指定下载,就下载该图片          
        //否则,就显示在浏览器中          
        FileInfo file = new FileInfo(serverpath);          
        Response.Clear( );  
        Response.AddHeader("Content-Disposition", "attachment;filename=" + Server.UrlEncode(this.ListBox1.SelectedValue));          
        Response.AddHeader("Content-Length", file.Length.ToString( ));          
        Response.ContentType = "application/octet-stream; charset=gb2312";          
        Response.Filter.Close( );          
        Response.WriteFile(file.FullName);          
        Response.End( );  
    }
View Code

 

posted on 2018-01-22 15:34  莫伊筱筱  阅读(172)  评论(0)    收藏  举报