18-WebService

WebService就是一種跨編程語(yǔ)言和跨操作系統(tǒng)平臺(tái)的遠(yuǎn)程調(diào)用技術(shù)。

一、資料準(zhǔn)備

后面的例子中需要用到一個(gè)學(xué)生信息的實(shí)體,如下:

public class StudentEntity
{
    public StudentEntity()
    {
        ;
    }
    public StudentEntity(int stuId, string stuName, string stuSex, string stuPhone, string stuMail)
    {
        this.StudentId = stuId;
        this.StudentName = stuName;
        this.StudentSex = stuSex;
        this.StudentPhone = stuPhone;
        this.StudentMail = stuMail;
    }
    public int StudentId { get; set; } //編號(hào)
    public string StudentName { get; set; } //學(xué)生性別
    public string StudentSex { get; set; } //學(xué)生性別
    public string StudentPhone { get; set; } //學(xué)生電話
    public string StudentMail { get; set; } //學(xué)生郵箱   
}

此文下面的內(nèi)容需要對(duì)Json格式數(shù)據(jù)進(jìn)行處理,Json處理類如下:

public class MyJson
{
    #region 將對(duì)象轉(zhuǎn)換為Json(支持實(shí)體、集合)
    public static string ToJsJson(object item)
    {
        JavaScriptSerializer serializer = new JavaScriptSerializer();
        string output = serializer.Serialize(item);
        return output;
    }
    #endregion

    #region 將Json字符串轉(zhuǎn)換為實(shí)體或集合
    public static T FromJsonTo<T>(string jsonString)
    {
        JavaScriptSerializer serializer = new JavaScriptSerializer();
        T jsonObject = serializer.Deserialize<T>(jsonString);
        return jsonObject;
    }
    #endregion

    #region 將DataTable轉(zhuǎn)換成Json字符串
    public static string DataTableToJson(DataTable dt)
    {
        StringBuilder jsonBuilder = new StringBuilder();
        //jsonBuilder.Append("{\"");
        //jsonBuilder.Append(dt.TableName.ToString());
        //jsonBuilder.Append("\":[");

        jsonBuilder.Append("[");
        for (int i = 0; i < dt.Rows.Count; i++)
        {
            jsonBuilder.Append("{");
            for (int j = 0; j < dt.Columns.Count; j++)
            {
                jsonBuilder.Append("\"");
                jsonBuilder.Append(dt.Columns[j].ColumnName);
                jsonBuilder.Append("\":\"");
                jsonBuilder.Append(dt.Rows[i][j].ToString());
                jsonBuilder.Append("\",");
            }
            jsonBuilder.Remove(jsonBuilder.Length - 1, 1);
            jsonBuilder.Append("},");
        }
        jsonBuilder.Remove(jsonBuilder.Length - 1, 1);
        jsonBuilder.Append("]");

        //jsonBuilder.Append("]");
        //jsonBuilder.Append("}");
        return jsonBuilder.ToString();
    } 
    #endregion

    #region 將DataRow轉(zhuǎn)換成Json數(shù)據(jù)
    public static string DataRowToJson(DataTable dt)
    {
        StringBuilder jsonBuilder = new StringBuilder();
        jsonBuilder.Append("{");
        for (int j = 0; j < dt.Columns.Count; j++)
        {
            jsonBuilder.Append("\"");
            jsonBuilder.Append(dt.Columns[j].ColumnName);
            jsonBuilder.Append("\":\"");
            jsonBuilder.Append(dt.Rows[0][j].ToString());
            jsonBuilder.Append("\",");
        }
        jsonBuilder.Remove(jsonBuilder.Length - 1, 1);
        jsonBuilder.Append("},");
        jsonBuilder.Remove(jsonBuilder.Length - 1, 1);
        return jsonBuilder.ToString();
    } 
    #endregion
}

此文下面的內(nèi)容需要模擬Post請(qǐng)求和Get請(qǐng)求,模擬請(qǐng)求的類如下:

public class HttpHelper
{
    #region 模擬Post請(qǐng)求
    public static string HttpPost(string Url, string postDataStr)
    {
        Encoding encoding = System.Text.Encoding.GetEncoding("UTF-8");
        byte[] data = encoding.GetBytes(postDataStr);

        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);
        request.Method = "POST";
        request.ContentType = "application/x-www-form-urlencoded";
        request.ContentLength = data.Length;

        //Encoding encoding = System.Text.Encoding.GetEncoding("UTF-8");
        //byte[] data = encoding.GetBytes(postDataStr);
        //request.ContentLength = data.Length;

        //request.ContentLength = Encoding.UTF8.GetByteCount(postDataStr);

        CookieContainer cookieContainer = new CookieContainer();
        request.CookieContainer = cookieContainer;
        Stream myRequestStream = request.GetRequestStream();

        myRequestStream.Write(data, 0, data.Length);
        //myStreamWriter.Write(data, 0, data.Length);
        myRequestStream.Close();


        //    //發(fā)送請(qǐng)求并獲取相應(yīng)回應(yīng)數(shù)據(jù)
        //    response = request.GetResponse() as HttpWebResponse;
        //    //直到request.GetResponse()程序才開(kāi)始向目標(biāo)網(wǎng)頁(yè)發(fā)送Post請(qǐng)求
        //    instream = response.GetResponseStream();
        //    sr = new StreamReader(instream, encoding);
        //    //返回結(jié)果網(wǎng)頁(yè)(html)代碼
        //    string content = sr.ReadToEnd();
        //    string err = string.Empty;
        //    return content;
        //    //}
        //    //catch (Exception ex)
        //    //{
        //    //    string err = ex.Message;
        //    //    return string.Empty;
        //    //}


        HttpWebResponse response = (HttpWebResponse)request.GetResponse();

        response.Cookies = cookieContainer.GetCookies(response.ResponseUri);
        Stream myResponseStream = response.GetResponseStream();

        StreamReader myStreamReader = new StreamReader(myResponseStream, encoding);
        string retString = myStreamReader.ReadToEnd();
        myStreamReader.Close();
        myResponseStream.Close();

        return retString;
    }
    #endregion

    #region 模擬Get請(qǐng)求
    public static string HttpGet(string Url, string postDataStr)
    {
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url + (postDataStr == "" ? "" : "?") + postDataStr);
        request.Method = "GET";
        request.ContentType = "text/html;charset=UTF-8";
        HttpWebResponse response = (HttpWebResponse)request.GetResponse();
        Stream myResponseStream = response.GetResponseStream();
        StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
        string retString = myStreamReader.ReadToEnd();
        myStreamReader.Close();
        myResponseStream.Close();
        return retString;
    }
    #endregion

    #region 智能教室的Post版本
    //public string HttpPost(string posturl, string postData)
    //{
    //    Stream outstream = null;
    //    Stream instream = null;
    //    StreamReader sr = null;
    //    HttpWebResponse response = null;
    //    HttpWebRequest request = null;
    //    Encoding encoding = System.Text.Encoding.GetEncoding("UTF-8");
    //    byte[] data = encoding.GetBytes(postData);
    //    // 準(zhǔn)備請(qǐng)求...
    //    //try
    //    //{
    //    // 設(shè)置參數(shù)
    //    request = WebRequest.Create(posturl) as HttpWebRequest;
    //    CookieContainer cookieContainer = new CookieContainer();
    //    request.CookieContainer = cookieContainer;
    //    request.AllowAutoRedirect = true;
    //    request.Method = "POST";
    //    request.ContentType = "application/x-www-form-urlencoded";
    //    request.ContentLength = data.Length;
    //    outstream = request.GetRequestStream();
    //    outstream.Write(data, 0, data.Length);
    //    outstream.Close();
    //    //發(fā)送請(qǐng)求并獲取相應(yīng)回應(yīng)數(shù)據(jù)
    //    response = request.GetResponse() as HttpWebResponse;
    //    //直到request.GetResponse()程序才開(kāi)始向目標(biāo)網(wǎng)頁(yè)發(fā)送Post請(qǐng)求
    //    instream = response.GetResponseStream();
    //    sr = new StreamReader(instream, encoding);
    //    //返回結(jié)果網(wǎng)頁(yè)(html)代碼
    //    string content = sr.ReadToEnd();
    //    string err = string.Empty;
    //    return content;
    //    //}
    //    //catch (Exception ex)
    //    //{
    //    //    string err = ex.Message;
    //    //    return string.Empty;
    //    //}
    //}
    #endregion
}

二、調(diào)用外部公開(kāi)服務(wù)

火車時(shí)刻表 WEB 服務(wù):

http://www.webxml.com.cn/WebServices/TrainTimeWebService.asmx

0095.PNG

(1)添加Web引用調(diào)用

步驟一:在項(xiàng)目中"添加服務(wù)引用"。

步驟二:編寫測(cè)試代碼:

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>調(diào)用火車時(shí)刻表 WEB 服務(wù)</title>
</head>
<body>
    <h2>
    火車時(shí)刻表 WEB 服務(wù):
    http://www.webxml.com.cn/WebServices/TrainTimeWebService.asmx
    </h2>
    <form id="form1" runat="server">
    <div>
        <p>
            出發(fā)地:<asp:TextBox ID="txtStart" runat="server"></asp:TextBox>
            到達(dá)地:<asp:TextBox ID="txtEnd" runat="server"></asp:TextBox>
            <asp:Button ID="btSelect" runat="server" Text="查詢列車" onclick="btSelect_Click" />       
        </p>
        <p>
            <asp:GridView ID="gvTrain" runat="server" AutoGenerateColumns="false" 
                Width="980px">
                <Columns>
                    <asp:BoundField DataField="TrainCode" HeaderText="車次" />
                    <asp:BoundField DataField="FirstStation" HeaderText="起點(diǎn)" />
                    <asp:BoundField DataField="LastStation" HeaderText="終點(diǎn)" />
                    <asp:BoundField DataField="StartStation" HeaderText="出發(fā)站" />
                    <asp:BoundField DataField="StartTime" HeaderText="出發(fā)時(shí)間" />
                    <asp:BoundField DataField="ArriveStation" HeaderText="到達(dá)站" />
                    <asp:BoundField DataField="ArriveTime" HeaderText="到達(dá)時(shí)間" />
                    <asp:BoundField DataField="UseDate" HeaderText="時(shí)長(zhǎng)" />
                </Columns>
            </asp:GridView>
        </p>
    </div>
    </form>
</body>
</html>
using ServiceReference1;
using System.Data;
public partial class Demo02 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        
    }

    protected void btSelect_Click(object sender, EventArgs e)
    {    
        TrainTimeWebServiceSoapClient client = new TrainTimeWebServiceSoapClient();
        DataTable dt = new DataTable();
        dt = client.getStationAndTimeByStationName(this.txtStart.Text, this.txtEnd.Text, "").Tables[0];
        this.gvTrain.DataSource = dt;
        this.gvTrain.DataBind();
    }
}

(2)Post調(diào)用

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <h2>
    火車時(shí)刻表 WEB 服務(wù):
    http://www.webxml.com.cn/WebServices/TrainTimeWebService.asmx
    </h2>
    <form id="form1" runat="server">
    <div>
        <p>
            出發(fā)地:<asp:TextBox ID="txtStart" runat="server"></asp:TextBox>
            到達(dá)地:<asp:TextBox ID="txtEnd" runat="server"></asp:TextBox>
            <asp:Button ID="btSelect" runat="server" Text="查詢列車" onclick="btSelect_Click" />       
        </p>
        <p>
            <asp:GridView ID="gvTrain" runat="server" AutoGenerateColumns="false" 
                Width="980px">
                <Columns>
                    <asp:BoundField DataField="TrainCode" HeaderText="車次" />
                    <asp:BoundField DataField="FirstStation" HeaderText="起點(diǎn)" />
                    <asp:BoundField DataField="LastStation" HeaderText="終點(diǎn)" />
                    <asp:BoundField DataField="StartStation" HeaderText="出發(fā)站" />
                    <asp:BoundField DataField="StartTime" HeaderText="出發(fā)時(shí)間" />
                    <asp:BoundField DataField="ArriveStation" HeaderText="到達(dá)站" />
                    <asp:BoundField DataField="ArriveTime" HeaderText="到達(dá)時(shí)間" />
                    <asp:BoundField DataField="UseDate" HeaderText="時(shí)長(zhǎng)" />
                </Columns>
            </asp:GridView>
        </p>
    </div>
    </form>
</body>
</html>
public partial class Demo02 : System.Web.UI.Page
{
    private string serviceUrl = "http://www.webxml.com.cn/WebServices/TrainTimeWebService.asmx/";
    protected void Page_Load(object sender, EventArgs e)
    {

    }

    protected void btSelect_Click(object sender, EventArgs e)
    {
        string url = serviceUrl + "getStationAndTimeByStationName";
        string xmlResult = HttpHelper.HttpPost(url, string.Format("StartStation={0}&ArriveStation={1}&UserID=",this.txtStart.Text,this.txtEnd.Text));

        XmlDocument xmlDoc = new XmlDocument();
        xmlDoc.LoadXml(xmlResult);
        //XmlNamespaceManager namespaceManager = new XmlNamespaceManager(xmlDoc.NameTable);
        //namespaceManager.AddNamespace("ns", "http://tempuri.org/");
        //namespaceManager.AddNamespace("diffgr", "urn:schemas-microsoft-com:xml-diffgram-v1");
        //XmlNodeList nodeList = xmlDoc.SelectNodes("/ns:DataTable/diffgr:diffgram/DocumentElement/ns:stuInfo", namespaceManager);
        XmlNodeList tableNodeList = xmlDoc.DocumentElement.ChildNodes[1].ChildNodes[0].ChildNodes;
        DataTable dt = new DataTable();
        dt.Columns.Add("TrainCode");
        dt.Columns.Add("FirstStation");
        dt.Columns.Add("LastStation");
        dt.Columns.Add("StartStation");
        dt.Columns.Add("StartTime");
        dt.Columns.Add("ArriveStation");
        dt.Columns.Add("ArriveTime");
        dt.Columns.Add("UseDate");
        for (int i = 0; i < tableNodeList.Count; i++)
        {
            DataRow dr = dt.NewRow();
            dr["TrainCode"] = tableNodeList[i].ChildNodes[0].InnerText;
            dr["FirstStation"] = tableNodeList[i].ChildNodes[1].InnerText;
            dr["LastStation"] = tableNodeList[i].ChildNodes[2].InnerText;
            dr["StartStation"] = tableNodeList[i].ChildNodes[3].InnerText;
            dr["StartTime"] = tableNodeList[i].ChildNodes[4].InnerText;
            dr["ArriveStation"] = tableNodeList[i].ChildNodes[5].InnerText;
            dr["ArriveTime"] = tableNodeList[i].ChildNodes[6].InnerText;
            dr["UseDate"] = tableNodeList[i].ChildNodes[8].InnerText;
            dt.Rows.Add(dr);
        }
        this.gvTrain.DataSource = dt;
        this.gvTrain.DataBind();


        //TrainTimeWebService service = new TrainTimeWebService();
        //DataTable dt = new DataTable();
        //dt = service.getStationAndTimeByStationName(this.txtStart.Text, this.txtEnd.Text, "").Tables[0];
        //this.gvTrain.DataSource = dt;
        //this.gvTrain.DataBind();
    }
}

三、編寫WebService

創(chuàng)建一個(gè)新的網(wǎng)站,在新網(wǎng)站中創(chuàng)建Web 服務(wù)“WebService.asmx”。Web服務(wù)創(chuàng)建成功之后會(huì)生成兩個(gè)文件:

(1)WebService.cs:在此文件中編寫自己的Web服務(wù)方法。

(2)WebService.asmx:web服務(wù)文件,可以通過(guò)瀏覽此文件得到服務(wù)地址以及服務(wù)的描述文件。

WebService提供的服務(wù)如下:

(1)public string HelloWorld():
    返回字符串;
(2)public string Add(int a,int b):
    返回字符串;
(3)public string[] GetAllStuName(string sex):
    返回字符串?dāng)?shù)組(根據(jù)性別求學(xué)生姓名,性別輸入空字符串代表所有學(xué)生姓名);
(4)public List<StudentEntity> GetAllStuInfo(string sex):
    返回學(xué)生類型泛型集合;
(5)public DataTable GetAllStuDataTable(string sex):
    返回存儲(chǔ)學(xué)生的DataTable
(6)public List<StudentEntity> AddOneStu(StudentEntity entity)
    復(fù)雜參數(shù)的傳遞-傳遞一個(gè)實(shí)體對(duì)象
(7)public List<StudentEntity> AddManyStu(List<StudentEntity> list)
    復(fù)雜對(duì)象的傳遞-傳遞一個(gè)泛型集合
(8)public string AddJsonString(string jsonString)
    接受一個(gè)Json字符串,返回Json數(shù)組
(9)public string AddJsonArrString(string jsonString)
    接受一個(gè)Json數(shù)組,返回Json數(shù)組
(10)public string[] UploadImage(string image)
    接受上傳圖片的接口(Base64轉(zhuǎn)碼上傳)

WebService.cs代碼如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Data;
using System.IO;
using System.Xml;

/// <summary>
///WebService 的摘要說(shuō)明
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
//若要允許使用 ASP.NET AJAX 從腳本中調(diào)用此 Web 服務(wù),請(qǐng)取消對(duì)下行的注釋。 
// [System.Web.Script.Services.ScriptService]
public class WebService : System.Web.Services.WebService 
{
    private List<StudentEntity> listStu = new List<StudentEntity>();
    public WebService () {
        //如果使用設(shè)計(jì)的組件,請(qǐng)取消注釋以下行 
        //InitializeComponent(); 
        listStu.Add(new StudentEntity(1, "劉備", "男", "13556878546", "liubei@163.com"));
        listStu.Add(new StudentEntity(2, "關(guān)羽", "男", "13698754521", "guanyu@163.com"));
        listStu.Add(new StudentEntity(3, "張飛", "男", "13512365412", "zhangfei@163.com"));
        listStu.Add(new StudentEntity(4, "趙云", "男", "13998986547", "zhaoyun@163.com"));
        listStu.Add(new StudentEntity(5, "馬超", "男", "13458745232", "machao@163.com"));
        listStu.Add(new StudentEntity(7, "大喬", "女", "13532234512", "zhangfei@163.com"));
        listStu.Add(new StudentEntity(8, "小喬", "女", "1391434579", "zhaoyun@163.com"));
        listStu.Add(new StudentEntity(9, "孫尚香", "女", "1347895159", "machao@163.com"));
    }

    #region 返回字符串
    [WebMethod]
    public string HelloWorld() {
        return "Hello World";
    }
    #endregion

    #region 返回字符串
    [WebMethod]
    public string Add(int a,int b)
    {
        return (a + b).ToString();
    }
    #endregion

    #region 返回字符串?dāng)?shù)組(根據(jù)性別求學(xué)生姓名,性別輸入空字符串代表所有學(xué)生姓名)
    [WebMethod]
    public string[] GetAllStuName(string sex)
    {
        if (!sex.Equals(""))
            listStu = listStu.Where(p => p.StudentSex.Equals(sex)).ToList();
        string[] arrName = new string[listStu.Count];
        for (int i = 0; i < listStu.Count; i++)
        {
            if (sex.Equals("") || sex.Equals(listStu[i].StudentSex))
                arrName[i] = listStu[i].StudentName;
        }
        return arrName;
        //return new string[3] { sex, sex, sex };
    }
    #endregion

    #region 返回學(xué)生類型泛型集合
    [WebMethod]
    public List<StudentEntity> GetAllStuInfo(string sex)
    {
        if (!sex.Equals(""))
            listStu = listStu.Where(p => p.StudentSex.Equals(sex)).ToList();
        return listStu;
    }
    #endregion

    #region 返回存儲(chǔ)學(xué)生的DataTable
    [WebMethod]
    public DataTable GetAllStuDataTable(string sex)
    {
        DataTable dt = new DataTable("stuInfo");
        dt.Columns.Add("StudentId");
        dt.Columns.Add("StudentName");
        dt.Columns.Add("StudentSex");
        dt.Columns.Add("StudentPhone");
        dt.Columns.Add("StudentMail");
        if (!sex.Equals(""))
            listStu = listStu.Where(p => p.StudentSex.Equals(sex)).ToList();
        foreach (StudentEntity item in listStu)
        {
            dt.Rows.Add(new object[] { item.StudentId, item.StudentName, item.StudentSex, item.StudentPhone, item.StudentMail });
        }
        return dt;
    }
    #endregion

    #region 復(fù)雜參數(shù)的傳遞-傳遞一個(gè)實(shí)體對(duì)象
    [WebMethod]
    public List<StudentEntity> AddOneStu(StudentEntity entity)
    {
        listStu.Add(entity);
        return listStu;
    }
    #endregion

    #region 復(fù)雜對(duì)象的傳遞-傳遞一個(gè)泛型集合
    [WebMethod]
     public List<StudentEntity> AddManyStu(List<StudentEntity> list)
     {
         listStu = listStu.Union(list).ToList();
         return listStu;
     }
    #endregion

    #region 接受一個(gè)Json字符串,返回Json數(shù)組
    [WebMethod]
    public string AddJsonString(string jsonString)
    {
        StudentEntity entity = MyJson.FromJsonTo<StudentEntity>(jsonString);
        listStu.Add(entity);
        return MyJson.ToJsJson(listStu);
    }
    #endregion

    #region 接受一個(gè)Json數(shù)組,返回Json數(shù)組
    [WebMethod]
    public string AddJsonArrString(string jsonString)
    {
        List<StudentEntity> list = MyJson.FromJsonTo<List<StudentEntity>>(jsonString);
        listStu = listStu.Union(list).ToList();
        return MyJson.ToJsJson(listStu);
    }
    #endregion

    public enum FileExtension
    {
        JPG = 255216,
        GIF = 7173,
        BMP = 6677,
        PNG = 13780,
        RAR = 8297,
        jpg = 255216,
        exe = 7790,
        xml = 6063,
        html = 6033,
        aspx = 239187,
        cs = 117115,
        js = 119105,
        txt = 210187,
        sql = 255254
    }

    [WebMethod]
    #region 接受上傳圖片的接口(Base64轉(zhuǎn)碼上傳)
    public string[] UploadImage(string image)
    {
        FileStream fsOut = null;
        image = image.Trim().Replace("%", "").Replace(",", "").Replace(" ", "+");
        byte[] bs = Convert.FromBase64String(image);
        
        #region 判斷文件類型
        MemoryStream ms = new MemoryStream(bs);
        System.IO.BinaryReader br = new System.IO.BinaryReader(ms);
        string fileclass = "";
        byte buffer;
        try
        {
            buffer = br.ReadByte();
            fileclass = buffer.ToString();
            buffer = br.ReadByte();
            fileclass += buffer.ToString();
        }
        catch
        {
        }
        br.Close();
        ms.Close();
        FileExtension[] fileEx = { FileExtension.GIF, FileExtension.JPG, FileExtension.PNG ,FileExtension.RAR};
        string fileFix = "";
        foreach (FileExtension fe in fileEx)
        {
            if (Int32.Parse(fileclass) == (int)fe)
                fileFix = fe.ToString();
        }
        if (fileFix.Equals(""))
            return (new string[] { "不支持此文件類型上傳" });
        #endregion
        
        string directory = "~/uploadimg/";
        //判斷目錄是否存在
        if (!Directory.Exists(HttpContext.Current.Server.MapPath(directory)))
            return (new string[]{ "上傳目錄有問(wèn)題"});
        //判斷文件是否存在
        //if (File.Exists(HttpContext.Current.Server.MapPath(directory + "\\" + filename)))
        //    File.Delete(HttpContext.Current.Server.MapPath(directory) + "\\" + filename);

        //String path = String.Format("{0:yyyyMMdd_hhmmss}_{1}", DateTime.Now, filename);
        string uploadFileName = DateTime.Now.ToString("yyyyMMddhhmmssfff") + "." + fileFix;
        String newFile = HttpContext.Current.Server.MapPath(directory + uploadFileName);     // 上傳文件存放路徑
        fsOut = new FileStream(newFile, FileMode.CreateNew, FileAccess.Write);
        try
        {
            fsOut.Write(bs, 0, bs.Length);
        }
        catch (IOException)
        {
            //  TODO Auto-generated catch block 
            return (new string[] { "上傳文件失敗" });
        }
        fsOut.Close();
        return (new string[] { "上傳成功", uploadFileName });
    }
    #endregion
}

四、添加Web引用方式調(diào)用WebService

本示例實(shí)現(xiàn)對(duì)前面我們自己編寫的WebService的調(diào)用。

步驟一:在項(xiàng)目中"添加Web引用"。

步驟二:編寫測(cè)試代碼:

ASPX代碼:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title>引用Web引用的方式調(diào)用Webservice</title>
</head>
<body>
    <form id="form1" runat="server">
        <p> 
            <h3>引用Web引用的方式調(diào)用Webservice</h3>
            <asp:Button ID="Button1" runat="server" Text="調(diào)用HelloWorld返回字符串" OnClick="Button1_Click" />
            <asp:Button ID="Button2" runat="server" Text="調(diào)用Add返回字符串" OnClick="Button2_Click" />
            <asp:Button ID="Button3" runat="server" Text="調(diào)用GetAllStuName返回字符串?dāng)?shù)組" OnClick="Button3_Click"   />        
        </p>
    <p>
        <asp:Button ID="Button4" runat="server" Text="調(diào)用GetAllStuInfo返回泛型集合" OnClick="Button4_Click" />
    </p>
    <p>
        <asp:GridView ID="gvStudent4" runat="server" AutoGenerateColumns="false">
            <Columns>
                <asp:BoundField DataField="StudentId" HeaderText="學(xué)生編號(hào)" />
                <asp:BoundField DataField="StudentName" HeaderText="學(xué)生姓名" />
                <asp:BoundField DataField="StudentSex" HeaderText="學(xué)生性別" />
                <asp:BoundField DataField="StudentPhone" HeaderText="學(xué)生電話" />
                <asp:BoundField DataField="StudentMail" HeaderText="學(xué)生郵箱" />
            </Columns>
        </asp:GridView>
    </p>

    <p>
        <asp:Button ID="Button5" runat="server" Text="調(diào)用GetAllStuDataTable返回DataTable" OnClick="Button5_Click"  />
    </p>
    <p>
        <asp:GridView ID="gvStudent5" runat="server" AutoGenerateColumns="false">
            <Columns>
                <asp:BoundField DataField="StudentId" HeaderText="學(xué)生編號(hào)" />
                <asp:BoundField DataField="StudentName" HeaderText="學(xué)生姓名" />
                <asp:BoundField DataField="StudentSex" HeaderText="學(xué)生性別" />
                <asp:BoundField DataField="StudentPhone" HeaderText="學(xué)生電話" />
                <asp:BoundField DataField="StudentMail" HeaderText="學(xué)生郵箱" />
            </Columns>
        </asp:GridView>
    </p>
    <p>
        <asp:Button ID="Button6" runat="server" Text="調(diào)用AddOneStu進(jìn)行實(shí)體對(duì)象的傳遞" OnClick="Button6_Click"  />
    </p>
    <p>
        <asp:GridView ID="gvStudent6" runat="server" AutoGenerateColumns="false">
            <Columns>
                <asp:BoundField DataField="StudentId" HeaderText="學(xué)生編號(hào)" />
                <asp:BoundField DataField="StudentName" HeaderText="學(xué)生姓名" />
                <asp:BoundField DataField="StudentSex" HeaderText="學(xué)生性別" />
                <asp:BoundField DataField="StudentPhone" HeaderText="學(xué)生電話" />
                <asp:BoundField DataField="StudentMail" HeaderText="學(xué)生郵箱" />
            </Columns>
        </asp:GridView>
    </p>
    <p>
        <asp:Button ID="Button7" runat="server" Text="調(diào)用AddManyStu進(jìn)行泛型集合的傳遞" OnClick="Button7_Click"  />
    </p>
    <p>
        <asp:GridView ID="gvStudent7" runat="server" AutoGenerateColumns="false">
            <Columns>
                <asp:BoundField DataField="StudentId" HeaderText="學(xué)生編號(hào)" />
                <asp:BoundField DataField="StudentName" HeaderText="學(xué)生姓名" />
                <asp:BoundField DataField="StudentSex" HeaderText="學(xué)生性別" />
                <asp:BoundField DataField="StudentPhone" HeaderText="學(xué)生電話" />
                <asp:BoundField DataField="StudentMail" HeaderText="學(xué)生郵箱" />
            </Columns>
        </asp:GridView>
    </p>
    <p>
        <asp:Button ID="Button8" runat="server" Text="調(diào)用AddJsonString傳遞一個(gè)Json字符串表示一個(gè)實(shí)體" OnClick="Button8_Click"   />
    </p>
    <p>
        <asp:GridView ID="gvStudent8" runat="server" AutoGenerateColumns="false">
            <Columns>
                <asp:BoundField DataField="StudentId" HeaderText="學(xué)生編號(hào)" />
                <asp:BoundField DataField="StudentName" HeaderText="學(xué)生姓名" />
                <asp:BoundField DataField="StudentSex" HeaderText="學(xué)生性別" />
                <asp:BoundField DataField="StudentPhone" HeaderText="學(xué)生電話" />
                <asp:BoundField DataField="StudentMail" HeaderText="學(xué)生郵箱" />
            </Columns>
        </asp:GridView>
    </p>
    <p>
        <asp:Button ID="Button9" runat="server" 
            Text="調(diào)用AddJsonArrString傳遞一個(gè)Json數(shù)組表示一個(gè)集合" OnClick="Button9_Click"   />
    </p>
    <p>
        <asp:GridView ID="gvStudent9" runat="server" AutoGenerateColumns="false">
            <Columns>
                <asp:BoundField DataField="StudentId" HeaderText="學(xué)生編號(hào)" />
                <asp:BoundField DataField="StudentName" HeaderText="學(xué)生姓名" />
                <asp:BoundField DataField="StudentSex" HeaderText="學(xué)生性別" />
                <asp:BoundField DataField="StudentPhone" HeaderText="學(xué)生電話" />
                <asp:BoundField DataField="StudentMail" HeaderText="學(xué)生郵箱" />
            </Columns>
        </asp:GridView>
    </p>
    <p>
    <asp:FileUpload ID="fileImg" runat="server" />
    <asp:Button ID="btUpload" runat="server" Text="調(diào)用上傳圖片服務(wù)" OnClick="btUpload_Click"  />
    </p>
    <p>
        <span id="spanUplodFile" runat="server" clientidmode="Static"></span>
        <asp:Image ID="imgUpload" runat="server" />
    </p>
    </form>
</body>
</html>

C#代碼:

//添加web引用,輸入webservice地址
//如需修改地址,到web.config文件中進(jìn)行修改
public partial class Demo01 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }

    #region 調(diào)用HelloWorld
    protected void Button1_Click(object sender, EventArgs e)
    {
        WebServiceSoapClient client = new WebServiceSoapClient();
        string res = client.HelloWorld();
        Page.ClientScript.RegisterStartupScript(this.GetType(),"JS","<script>alert('"+res+"');</script>");
    }
    #endregion

    #region 調(diào)用Add
    protected void Button2_Click(object sender, EventArgs e)
    {
        WebServiceSoapClient client = new WebServiceSoapClient();
        string res = client.Add(2, 3);
        Page.ClientScript.RegisterStartupScript(this.GetType(), "JS", "<script>alert('" + res + "');</script>");
    }
    #endregion

    #region 調(diào)用GetAllStuName返回字符串?dāng)?shù)組
    protected void Button3_Click(object sender, EventArgs e)
    {
        WebServiceSoapClient client = new WebServiceSoapClient();
        string[] arr = client.GetAllStuName("女");
        string res = string.Join(",", arr);
        Page.ClientScript.RegisterStartupScript(this.GetType(), "JS", "<script>alert('" + res + "');</script>");
    }
    #endregion

    #region 調(diào)用GetAllStuInfo返回集合,使用對(duì)象數(shù)組接受
    protected void Button4_Click(object sender, EventArgs e)
    {
        WebServiceSoapClient client = new WebServiceSoapClient();
        StudentEntity[] arr = client.GetAllStuInfo("女");
        this.gvStudent4.DataSource = arr;
        this.gvStudent4.DataBind();
    }
    #endregion

    #region 調(diào)用GetAllStuDataTable返回DataTable
    protected void Button5_Click(object sender, EventArgs e)
    {
        WebServiceSoapClient client = new WebServiceSoapClient();
        DataTable dt = client.GetAllStuDataTable("男");
        this.gvStudent5.DataSource = dt;
        this.gvStudent5.DataBind();
    }
    #endregion

    #region 調(diào)用AddOneStu進(jìn)行實(shí)體對(duì)象的傳遞
    protected void Button6_Click(object sender, EventArgs e)
    {
        StudentEntity entity = new StudentEntity();
        entity.StudentId = 10;
        entity.StudentName = "呂布";
        entity.StudentSex = "男";
        entity.StudentPhone = "15585695123";
        entity.StudentMail = "lb@163.com";
        WebServiceSoapClient client = new WebServiceSoapClient();
        StudentEntity[] arr = client.AddOneStu(entity);
        this.gvStudent6.DataSource = arr;
        this.gvStudent6.DataBind();
    }
    #endregion

    #region 調(diào)用AddManyStu復(fù)雜對(duì)象的傳遞-傳遞一個(gè)泛型集合
    protected void Button7_Click(object sender, EventArgs e)
    {
        StudentEntity entity1 = new StudentEntity();
        entity1.StudentId = 10;
        entity1.StudentName = "呂布";
        entity1.StudentSex = "男";
        entity1.StudentPhone = "15585695123";
        entity1.StudentMail = "lb@163.com";
        StudentEntity entity2 = new StudentEntity();
        entity2.StudentId = 11;
        entity2.StudentName = "曹操";
        entity2.StudentSex = "男";
        entity2.StudentPhone = "15447859632";
        entity2.StudentMail = "cc@163.com";
        List<StudentEntity> list = new List<StudentEntity>();
        list.Add(entity1);
        list.Add(entity2);
        WebServiceSoapClient client = new WebServiceSoapClient();
        StudentEntity[] arr = client.AddManyStu(list.ToArray());
        this.gvStudent7.DataSource = arr;
        this.gvStudent7.DataBind();
    }
    #endregion

    #region 調(diào)用AddJsonString傳遞一個(gè)Json字符串表示一個(gè)實(shí)體
    protected void Button8_Click(object sender, EventArgs e)
    {
        StudentEntity entity = new StudentEntity();
        entity.StudentId = 10;
        entity.StudentName = "呂布";
        entity.StudentSex = "男";
        entity.StudentPhone = "15585695123";
        entity.StudentMail = "lb@163.com";
        string strStu = MyJson.ToJsJson(entity);
        WebServiceSoapClient client = new WebServiceSoapClient();
        string res = client.AddJsonString(strStu);
        List<StudentEntity> list = MyJson.FromJsonTo<List<StudentEntity>>(res);
        this.gvStudent8.DataSource = list;
        this.gvStudent8.DataBind();

    }

    //如果不想使用StudentEntity強(qiáng)數(shù)據(jù)類型接受返回的數(shù)組,可以使用List<object>接受
    //接受之后每一行為一個(gè)dictionary鍵值對(duì),從鍵值對(duì)取值到匿名類集合中
    //protected void Button8_Click(object sender, EventArgs e)
    //{
    //    //StudentEntity已經(jīng)被序列化,所以這里轉(zhuǎn)Json后的字段名會(huì)發(fā)生改變
    //    StudentEntity entity = new StudentEntity();
    //    entity.StudentId = 10;
    //    entity.StudentName = "呂布";
    //    entity.StudentSex = "男";
    //    entity.StudentPhone = "15365878563";
    //    entity.StudentMail = "lvbu@163.com";

    //    string jsonStr = MyJson.ToJsJson(entity);

    //    WebService service = new WebService();
    //    string jsonResult = service.AddJsonString(jsonStr);

    //    List<object> listObj = MyJson.FromJsonTo<List<object>>(jsonResult); //Json轉(zhuǎn)object集合
    //    List<object> listResult = new List<object>();
    //    foreach (Dictionary<string, object> item in listObj)
    //    {
    //        listResult.Add(new {
    //            StudentId = item["StudentId"].ToString(),
    //            StudentName = item["StudentName"].ToString(),
    //            StudentSex = item["StudentSex"].ToString(),
    //            StudentPhone = item["StudentPhone"].ToString(),
    //            StudentMail = item["StudentMail"].ToString()
    //        });
    //    }

    //    this.gvStudent5.DataSource = listResult;
    //    this.gvStudent5.DataBind();

    //}
    #endregion

    #region 調(diào)用AddJsonArrString傳遞一個(gè)Json數(shù)組表示一個(gè)集合
    protected void Button9_Click(object sender, EventArgs e)
    {
        StudentEntity entity1 = new StudentEntity();
        entity1.StudentId = 10;
        entity1.StudentName = "呂布";
        entity1.StudentSex = "男";
        entity1.StudentPhone = "15585695123";
        entity1.StudentMail = "lb@163.com";
        StudentEntity entity2 = new StudentEntity();
        entity2.StudentId = 11;
        entity2.StudentName = "曹操";
        entity2.StudentSex = "男";
        entity2.StudentPhone = "15447859632";
        entity2.StudentMail = "cc@163.com";
        List<StudentEntity> list = new List<StudentEntity>();
        list.Add(entity1);
        list.Add(entity2);
        string strStu = MyJson.ToJsJson(list);
        WebServiceSoapClient client = new WebServiceSoapClient();
        string res = client.AddJsonArrString(strStu);
        List<StudentEntity> listRes = MyJson.FromJsonTo<List<StudentEntity>>(res);
        this.gvStudent9.DataSource = listRes;
        this.gvStudent9.DataBind();
    }
    #endregion

    #region 調(diào)用上傳圖片的服務(wù)
    protected void btUpload_Click(object sender, EventArgs e)
    {
        int fileLen = this.fileImg.PostedFile.ContentLength;
        byte[] imgArr = new byte[fileLen];
        this.fileImg.PostedFile.InputStream.Read(imgArr, 0, fileLen);
        string base64Str = Convert.ToBase64String(imgArr);
        WebServiceSoapClient client = new WebServiceSoapClient();
        string[] arrRes = client.UploadImage(base64Str);
        this.spanUplodFile.InnerHtml = arrRes[0];
        if (arrRes[0].Equals("上傳成功"))
        {
            this.imgUpload.ImageUrl = "http://localhost:18229/uploadimg/" + arrRes[1];
        }
    }
    #endregion
}

五、Post調(diào)用WebService

本示例實(shí)現(xiàn)對(duì)前面我們自己編寫的WebService的調(diào)用。

ASPX代碼:

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <p> 
        <h3>Post方式調(diào)用Webservice</h3>
        <asp:Button ID="Button1" runat="server" Text="調(diào)用HelloWorld返回字符串" 
        onclick="Button1_Click" />
        <asp:Button ID="Button2" runat="server" Text="調(diào)用Add返回字符串" 
        onclick="Button2_Click" />
        <asp:Button ID="Button3" runat="server" Text="調(diào)用GetAllStuName返回字符串?dāng)?shù)組" 
        onclick="Button3_Click"  />        
    </p>
    <p>
        <asp:Button ID="Button4" runat="server" Text="調(diào)用GetAllStuInfo返回泛型集合" 
            onclick="Button4_Click" />
    </p>
    <p>
        <asp:GridView ID="gvStudent1" runat="server" AutoGenerateColumns="false">
            <Columns>
                <asp:BoundField DataField="StudentId" HeaderText="學(xué)生編號(hào)" />
                <asp:BoundField DataField="StudentName" HeaderText="學(xué)生姓名" />
                <asp:BoundField DataField="StudentSex" HeaderText="學(xué)生性別" />
                <asp:BoundField DataField="StudentPhone" HeaderText="學(xué)生電話" />
                <asp:BoundField DataField="StudentMail" HeaderText="學(xué)生郵箱" />
            </Columns>
        </asp:GridView>
    </p>
    <p>
        <asp:Button ID="Button5" runat="server" Text="調(diào)用GetAllStuDataTable返回DataTable" 
            onclick="Button5_Click" />
    </p>
    <p>
        <asp:GridView ID="gvStudent2" runat="server" AutoGenerateColumns="false">
            <Columns>
                <asp:BoundField DataField="StudentId" HeaderText="學(xué)生編號(hào)" />
                <asp:BoundField DataField="StudentName" HeaderText="學(xué)生姓名" />
                <asp:BoundField DataField="StudentSex" HeaderText="學(xué)生性別" />
                <asp:BoundField DataField="StudentPhone" HeaderText="學(xué)生電話" />
                <asp:BoundField DataField="StudentMail" HeaderText="學(xué)生郵箱" />
            </Columns>
        </asp:GridView>
    </p>
    <p>
        <asp:Button ID="Button6" runat="server" Text="調(diào)用AddOneStu進(jìn)行實(shí)體對(duì)象的傳遞" 
            onclick="Button6_Click" />
    </p>
    <p>
        <asp:GridView ID="gvStudent3" runat="server" AutoGenerateColumns="false">
            <Columns>
                <asp:BoundField DataField="StudentId" HeaderText="學(xué)生編號(hào)" />
                <asp:BoundField DataField="StudentName" HeaderText="學(xué)生姓名" />
                <asp:BoundField DataField="StudentSex" HeaderText="學(xué)生性別" />
                <asp:BoundField DataField="StudentPhone" HeaderText="學(xué)生電話" />
                <asp:BoundField DataField="StudentMail" HeaderText="學(xué)生郵箱" />
            </Columns>
        </asp:GridView>
    </p>
    <p>
        <asp:Button ID="Button7" runat="server" Text="調(diào)用AddManyStu進(jìn)行泛型集合的傳遞" 
            onclick="Button7_Click"  />
    </p>
    <p>
        <asp:GridView ID="gvStudent4" runat="server" AutoGenerateColumns="false">
            <Columns>
                <asp:BoundField DataField="StudentId" HeaderText="學(xué)生編號(hào)" />
                <asp:BoundField DataField="StudentName" HeaderText="學(xué)生姓名" />
                <asp:BoundField DataField="StudentSex" HeaderText="學(xué)生性別" />
                <asp:BoundField DataField="StudentPhone" HeaderText="學(xué)生電話" />
                <asp:BoundField DataField="StudentMail" HeaderText="學(xué)生郵箱" />
            </Columns>
        </asp:GridView>
    </p>
    <p>
        <asp:Button ID="Button8" runat="server" Text="調(diào)用AddJsonString傳遞一個(gè)Json字符串表示一個(gè)實(shí)體" 
            onclick="Button8_Click"   />
    </p>
    <p>
        <asp:GridView ID="gvStudent5" runat="server" AutoGenerateColumns="false">
            <Columns>
                <asp:BoundField DataField="StudentId" HeaderText="學(xué)生編號(hào)" />
                <asp:BoundField DataField="StudentName" HeaderText="學(xué)生姓名" />
                <asp:BoundField DataField="StudentSex" HeaderText="學(xué)生性別" />
                <asp:BoundField DataField="StudentPhone" HeaderText="學(xué)生電話" />
                <asp:BoundField DataField="StudentMail" HeaderText="學(xué)生郵箱" />
            </Columns>
        </asp:GridView>
    </p>
    <p>
        <asp:Button ID="Button9" runat="server" 
            Text="調(diào)用AddJsonArrString傳遞一個(gè)Json數(shù)組表示一個(gè)集合" onclick="Button9_Click"  />
    </p>
    <p>
        <asp:GridView ID="gvStudent6" runat="server" AutoGenerateColumns="false">
            <Columns>
                <asp:BoundField DataField="StudentId" HeaderText="學(xué)生編號(hào)" />
                <asp:BoundField DataField="StudentName" HeaderText="學(xué)生姓名" />
                <asp:BoundField DataField="StudentSex" HeaderText="學(xué)生性別" />
                <asp:BoundField DataField="StudentPhone" HeaderText="學(xué)生電話" />
                <asp:BoundField DataField="StudentMail" HeaderText="學(xué)生郵箱" />
            </Columns>
        </asp:GridView>
    </p>
    <p>
    <asp:FileUpload ID="fileImg" runat="server" />
    <asp:Button ID="btUpload" runat="server" Text="調(diào)用上傳圖片服務(wù)" 
            onclick="btUpload_Click" /></p>
    <p>
        <span id="spanUplodFile" runat="server" clientidmode="Static"></span>
        <asp:Image ID="imgUpload" runat="server" />
    </p>
    
    </form>
</body>
</html>

C#代碼:

public partial class Demo01 : System.Web.UI.Page
{
    public class StudentEntity
    {
        public int StudentId { get; set; } //編號(hào)

        public string StudentName { get; set; } //學(xué)生性別

        public string StudentSex { get; set; } //學(xué)生性別

        public string StudentPhone { get; set; } //學(xué)生電話

        public string StudentMail { get; set; } //學(xué)生郵箱
    }

    private string serviceUrl = "http://localhost:2352/MyService/WebService.asmx/";

    protected void Page_Load(object sender, EventArgs e)
    {

    }

    #region 調(diào)用HelloWorld
    protected void Button1_Click(object sender, EventArgs e)
    {
        string url = serviceUrl + "HelloWorld";
        string xmlResult = HttpHelper.HttpPost(url, string.Empty);
        XmlDocument xmlDoc = new XmlDocument();
        xmlDoc.LoadXml(xmlResult);
        string strResult = xmlDoc.GetElementsByTagName("string")[0].InnerText;
        Page.ClientScript.RegisterStartupScript(this.GetType(), "js", "<script>alert('" + strResult + "');</script>");
    }
    #endregion

    #region 調(diào)用Add
    protected void Button2_Click(object sender, EventArgs e)
    {
        string url = serviceUrl + "Add";
        string xmlResult = HttpHelper.HttpPost(url, "a=2&b=4");
        XmlDocument xmlDoc = new XmlDocument();
        xmlDoc.LoadXml(xmlResult);
        string strResult = xmlDoc.GetElementsByTagName("string")[0].InnerText;
        Page.ClientScript.RegisterStartupScript(this.GetType(), "js", "<script>alert('" + strResult + "');</script>");
    }
    #endregion

    #region 調(diào)用GetAllStuName返回字符串?dāng)?shù)組
    protected void Button3_Click(object sender, EventArgs e)
    {
        string url = serviceUrl + "GetAllStuName";
        string xmlResult = HttpHelper.HttpPost(url, "sex=男");
        XmlDocument xmlDoc = new XmlDocument();
        xmlDoc.LoadXml(xmlResult);
        XmlNodeList nodeList = xmlDoc.DocumentElement.GetElementsByTagName("string");
        string[] arrName = new string[nodeList.Count];
        for (int i = 0; i < nodeList.Count; i++)
        {
            arrName[i] = nodeList[i].InnerText;
        }
        Page.ClientScript.RegisterStartupScript(this.GetType(), "js", "<script>alert('" + String.Join(",", arrName) + "');</script>");

        //XmlElement root = xmlDoc.DocumentElement; //根
        //string nameSpace = root.NamespaceURI;
        //XmlNamespaceManager namespaceManager = new XmlNamespaceManager(xmlDoc.NameTable);
        //namespaceManager.AddNamespace("ns",nameSpace);
        //string xPath = "/ArrayOfString/ns:string[1]";
        //XmlNode nodeList = root.SelectSingleNode(xPath, namespaceManager);
        //string str = "aaa";
        //XmlNamespaceManager namespaceManager = new XmlNamespaceManager(xmlDoc.NameTable); //namespace 
        //namespaceManager.AddNamespace("xsi", "http://www.w3.org/2001/XMLSchema-instance");
        //namespaceManager.AddNamespace("xsd", "http://www.w3.org/2001/XMLSchema");
        //namespaceManager.AddNamespace("ddd", "http://tempuri.org/");
        //XmlNode node = xmlDoc.SelectSingleNode(@"/ddd:ArrayOfString", namespaceManager);
        //bool b = node.HasChildNodes;
        //XmlNodeList nodeList = node.SelectSingleNode;
        //string[] arrName = new string[nodeList.Count];
        //for (int i = 0; i < nodeList.Count; i++)
        //{
        //    arrName[i] = nodeList[i].InnerText;
        //}
        //Page.ClientScript.RegisterStartupScript(this.GetType(), "js", "<script>alert('" + String.Join(",", arrName) + "');</script>");
        
    }
    #endregion

    #region 調(diào)用GetAllStuInfo返回集合,使用對(duì)象數(shù)組接受
    protected void Button4_Click(object sender, EventArgs e)
    {
        string url = serviceUrl + "GetAllStuInfo";
        string xmlResult = HttpHelper.HttpPost(url, "sex=男");
        XmlDocument xmlDoc = new XmlDocument();
        xmlDoc.LoadXml(xmlResult);
        XmlNodeList nodeList = xmlDoc.DocumentElement.GetElementsByTagName("StudentEntity");
        ArrayList stuList = new ArrayList();
        for (int i = 0; i < nodeList.Count; i++)
        {
            var stu = new { StudentId = nodeList[i].ChildNodes[0].InnerText,
                            StudentName = nodeList[i].ChildNodes[1].InnerText,
                            StudentSex = nodeList[i].ChildNodes[2].InnerText,
                            StudentPhone = nodeList[i].ChildNodes[3].InnerText,
                            StudentMail = nodeList[i].ChildNodes[4].InnerText
            };
            stuList.Add(stu);
        }
        this.gvStudent1.DataSource = stuList;
        this.gvStudent1.DataBind();

        //WebService service = new WebService();
        //StudentEntity[] arrStu = service.GetAllStuInfo("男");
        //this.gvStudent1.DataSource = arrStu;
        //this.gvStudent1.DataBind();

    }
    #endregion

    #region 調(diào)用GetAllStuDataTable返回DataTable
    protected void Button5_Click(object sender, EventArgs e)
    {
        string url = serviceUrl + "GetAllStuDataTable";
        string xmlResult = HttpHelper.HttpPost(url, "sex=男");
        XmlDocument xmlDoc = new XmlDocument();
        xmlDoc.LoadXml(xmlResult);
        //XmlNamespaceManager namespaceManager = new XmlNamespaceManager(xmlDoc.NameTable);
        //namespaceManager.AddNamespace("ns", "http://tempuri.org/");
        //namespaceManager.AddNamespace("diffgr", "urn:schemas-microsoft-com:xml-diffgram-v1");
        //XmlNodeList nodeList = xmlDoc.SelectNodes("/ns:DataTable/diffgr:diffgram/DocumentElement/ns:stuInfo", namespaceManager);
        XmlNodeList tableNodeList = xmlDoc.DocumentElement.ChildNodes[1].ChildNodes[0].ChildNodes;
        DataTable dt = new DataTable();
        dt.Columns.Add("StudentId");
        dt.Columns.Add("StudentName");
        dt.Columns.Add("StudentSex");
        dt.Columns.Add("StudentPhone");
        dt.Columns.Add("StudentMail");
        for (int i = 0; i < tableNodeList.Count; i++)
        {
            DataRow dr = dt.NewRow();
            dr["StudentId"] = tableNodeList[i].ChildNodes[0].InnerText;
            dr["StudentName"] = tableNodeList[i].ChildNodes[1].InnerText;
            dr["StudentSex"] = tableNodeList[i].ChildNodes[2].InnerText;
            dr["StudentPhone"] = tableNodeList[i].ChildNodes[3].InnerText;
            dr["StudentMail"] = tableNodeList[i].ChildNodes[4].InnerText;
            dt.Rows.Add(dr);
        }
        this.gvStudent2.DataSource = dt;
        this.gvStudent2.DataBind();

        //WebService service = new WebService();
        //DataTable dt = service.GetAllStuDataTable("");
        //this.gvStudent2.DataSource = dt;
        //this.gvStudent2.DataBind();
    }
    #endregion

    #region 調(diào)用AddOneStu進(jìn)行實(shí)體對(duì)象的傳遞
    protected void Button6_Click(object sender, EventArgs e)
    {
        //AddOneStu需要傳遞一個(gè)實(shí)體
        //此接口無(wú)法傳遞參數(shù),只能修改webservice接受字符串,然后將字符串轉(zhuǎn)換成xml進(jìn)行處理
    }
    #endregion

    #region 調(diào)用AddManyStu復(fù)雜對(duì)象的傳遞-傳遞一個(gè)泛型集合
    protected void Button7_Click(object sender, EventArgs e)
    {
        //AddManyStu需要傳遞一個(gè)實(shí)體
        //此接口無(wú)法傳遞參數(shù),只能修改webservice接受字符串,然后將字符串轉(zhuǎn)換成xml進(jìn)行處理
    }
    #endregion

    #region 調(diào)用AddJsonString傳遞一個(gè)Json字符串表示一個(gè)實(shí)體
    protected void Button8_Click(object sender, EventArgs e)
    {
        //將實(shí)體轉(zhuǎn)換成Json字符串
        Object Student = new
        {
            StudentId = 10,
            StudentName = "呂布",
            StudentSex = "男",
            StudentPhone = "15365878563",
            StudentMail = "lvbu@163.com"
        };
        string jsonStr = MyJson.ToJsJson(Student);
        string url = serviceUrl + "AddJsonString";
        string xmlResult = HttpHelper.HttpPost(url, "jsonString="+jsonStr);
        XmlDocument xmlDoc = new XmlDocument();
        xmlDoc.LoadXml(xmlResult);
        string jsonResult = xmlDoc.GetElementsByTagName("string")[0].InnerText;
        List<StudentEntity> list = new List<StudentEntity>();
        list = MyJson.FromJsonTo<List<StudentEntity>>(jsonResult);
        this.gvStudent5.DataSource = list;
        this.gvStudent5.DataBind();

        //StudentEntity已經(jīng)被序列化,所以這里轉(zhuǎn)Json后的字段名會(huì)發(fā)生改變
        //StudentEntity entity = new StudentEntity();
        //entity.StudentId = 10;
        //entity.StudentName = "呂布";
        //entity.StudentSex = "男";
        //entity.StudentPhone = "15365878563";
        //entity.StudentMail = "lvbu@163.com";

        //Object Student = new { StudentId = 10,
        //    StudentName = "呂布",
        //    StudentSex = "男",
        //    StudentPhone = "15365878563",
        //    StudentMail = "lvbu@163.com"};

        //string jsonStr = MyJson.ToJsJson(entity);

        //WebService service = new WebService();
        //StudentEntity[] arrStu = service.AddJsonString(jsonStr);
        //this.gvStudent5.DataSource = arrStu;
        //this.gvStudent5.DataBind();

    }
    #endregion

    #region 調(diào)用AddJsonArrString傳遞一個(gè)Json數(shù)組表示一個(gè)集合
    protected void Button9_Click(object sender, EventArgs e)
    {
        //將泛型集合轉(zhuǎn)換成Json字符串
        List<StudentEntity> listStu = new List<StudentEntity>();
        StudentEntity entity1 = new StudentEntity();
        entity1.StudentId = 10;
        entity1.StudentName = "呂布";
        entity1.StudentSex = "男";
        entity1.StudentPhone = "15365878563";
        entity1.StudentMail = "lvbu@163.com";
        listStu.Add(entity1);
        StudentEntity entity2 = new StudentEntity();
        entity2.StudentId = 11;
        entity2.StudentName = "曹操";
        entity2.StudentSex = "男";
        entity2.StudentPhone = "15334534578";
        entity2.StudentMail = "caocao@163.com";
        listStu.Add(entity2);
        string jsonStr = MyJson.ToJsJson(listStu);

        string url = serviceUrl + "AddJsonArrString";
        string xmlResult = HttpHelper.HttpPost(url, "jsonString=" + jsonStr);
        XmlDocument xmlDoc = new XmlDocument();
        xmlDoc.LoadXml(xmlResult);
        string jsonResult = xmlDoc.GetElementsByTagName("string")[0].InnerText;
        List<StudentEntity> list = new List<StudentEntity>();
        list = MyJson.FromJsonTo<List<StudentEntity>>(jsonResult);
        this.gvStudent6.DataSource = list;
        this.gvStudent6.DataBind();


        //List<StudentEntity> listStu = new List<StudentEntity>();
        //StudentEntity entity1 = new StudentEntity();
        //entity1.StudentId = 10;
        //entity1.StudentName = "呂布";
        //entity1.StudentSex = "男";
        //entity1.StudentPhone = "15365878563";
        //entity1.StudentMail = "lvbu@163.com";
        //listStu.Add(entity1);
        //StudentEntity entity2 = new StudentEntity();
        //entity2.StudentId = 11;
        //entity2.StudentName = "曹操";
        //entity2.StudentSex = "男";
        //entity2.StudentPhone = "15334534578";
        //entity2.StudentMail = "caocao@163.com";
        //listStu.Add(entity2);
        //string jsonStr = MyJson.ToJsJson(listStu);

        //WebService service = new WebService();
        //StudentEntity[] arrStu = service.AddJsonArrString(jsonStr);
        //this.gvStudent6.DataSource = arrStu;
        //this.gvStudent6.DataBind();
    }
    #endregion

    #region 調(diào)用上傳圖片的服務(wù)
    protected void btUpload_Click(object sender, EventArgs e)
    {
        int fileLen = this.fileImg.PostedFile.ContentLength;
        byte[] imgArray = new byte[fileLen];
        this.fileImg.PostedFile.InputStream.Read(imgArray, 0, fileLen);
        string base64Str = Convert.ToBase64String(imgArray);
        //由于網(wǎng)頁(yè)傳遞參數(shù)時(shí),會(huì)將加號(hào)編碼成空格,但是在解碼時(shí)卻不會(huì)解碼空格
        base64Str = base64Str.Replace("+", "%2B");

        string url = serviceUrl + "UploadImage";
        string xmlResult = HttpHelper.HttpPost(url, "image=" + base64Str);
        XmlDocument xmlDoc = new XmlDocument();
        xmlDoc.LoadXml(xmlResult);
        XmlNodeList nodeList = xmlDoc.DocumentElement.GetElementsByTagName("string");
        this.spanUplodFile.InnerHtml = nodeList[0].InnerText;
        if (nodeList[0].InnerText.Equals("上傳成功"))
        {
            this.imgUpload.ImageUrl = "http://localhost:2352/MyService/uploadimg/" + nodeList[1].InnerText;
        }


        //int fileLen = this.fileImg.PostedFile.ContentLength;
        //byte[] imgArray = new byte[fileLen];
        //this.fileImg.PostedFile.InputStream.Read(imgArray, 0, fileLen);
        //string base64Str = Convert.ToBase64String(imgArray);
        //由于網(wǎng)頁(yè)傳遞參數(shù)時(shí),會(huì)將加號(hào)編碼成空格,但是在解碼時(shí)卻不會(huì)解碼空格
        //base64Str = base64Str.Replace("+", "%2B");
        //WebService service = new WebService();
        //string[] arrResult = service.UploadImage(base64Str);
        //this.spanUplodFile.InnerHtml = arrResult[0];
        //if (arrResult[0].Equals("上傳成功"))
        //{
        //    this.imgUpload.ImageUrl = "http://localhost:2352/MyService/uploadimg/" + arrResult[1];
        //}
    }
    #endregion
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容