WCF學習之旅—實現支持REST客戶端應用(二十四)


            WCF學習之旅—實現REST服務(二十二)

           WCF學習之旅—實現支持REST服務端應用(二十三)

          在上二篇文章中簡單介紹了一下RestFul與WCF支持RestFul所提供的方法,及創建一個支持REST的WCF服務端程序,本文介紹如何調用上一篇文章介紹的RestFul服務端。

 

五、Windows客戶端調用

          為了強調REST的通用性,客戶端不用WCF的形式調用服務,而是采用HttpWebResponse通過編程方式直接訪問,消息格式我們選XML。

         首先,我們使用C#來封裝一個RestHelper類,實現HTTP的GET和POST的請求方法,代碼如下。

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Web;
 

namespace WinClient
{

    public class RestHelper
    {      

            /// <summary>
            /// 構造函數
            /// </summary>
            /// <param name="baseUrl"></param>
            public RestHelper(string baseUri)
            {

                this.BaseUri = baseUri;
            } 

            /// <summary>
            /// 基地址
            /// </summary>
            private string BaseUri; 

            /// <summary>
            /// Post調用
            /// </summary>
            /// <param name="data"></param>
            /// <param name="uri"></param>
            /// <returns></returns>
            public string Post(string data, string uri)
            {

                //Web訪問對象
                string serviceUrl = string.Format("{0}/{1}", this.BaseUri, uri);

                HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(serviceUrl);
                //轉成網絡流
                byte[] buf = UnicodeEncoding.UTF8.GetBytes(data); 

                //設置
                myRequest.Method = "POST";
                myRequest.ContentLength = buf.Length;
                myRequest.ContentType = "text/html";
 

                // 發送請求
                Stream newStream = myRequest.GetRequestStream();

                newStream.Write(buf, 0, buf.Length);
                newStream.Close(); 

                // 獲得接口返回值
                HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse();

                StreamReader reader = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8);

                string ReturnXml = HttpUtility.HtmlDecode(reader.ReadToEnd());

                reader.Close();
                myResponse.Close();
                return ReturnXml;

            }

            /// <summary>
            /// Get調用
            /// </summary>
            /// <param name="uri"></param>
            /// <returns></returns>
            public string Get(string uri)
            {

                //Web訪問對象
                string serviceUrl = string.Format("{0}/{1}", this.BaseUri, uri);

            HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(serviceUrl);

             // 獲得接口返回值
              HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse();

              StreamReader reader = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8);

              string ReturnXml = HttpUtility.UrlDecode(reader.ReadToEnd());

              reader.Close();
           myResponse.Close();
           return ReturnXml;
         }
    }

}

 

         其次,我們來實現主函數,按順序調用兩個接口,並顯示返回值。需要注意XML約定的命名空間。

         我們在visual studio 2015中創建一個Windows窗體,名稱為Form1,在Form1中放兩個按鈕,一個是“Rest Get”,另一個是"Rest Post"。

         1)在“Rest Get”按鈕中實現Get方法,代碼如下:

 private void buttonRest_Click(object sender, EventArgs e)
        {
            RestHelper client = new RestHelper("http://127.0.0.1:8888/");

            //Get
            string uriGet = string.Format("Books/Get/{0}", "2");
            string getData = client.Get(uriGet);
            textBoxMsg.Text = getData;
        }

 

     2) 在visual studio 2015中啟動客戶端應用程序,然后使用鼠標點擊“Rest Get”按鈕,結果如下圖。

 

 

          3)在“Rest Post”按鈕中實現Post方法,代碼如下:    

  private void buttonRestPost_Click(object sender, EventArgs e)
        {

            RestHelper client = new RestHelper("http://127.0.0.1:8888/");
            //Post

            string uriPost = "Books/Add";
            string data = "<Books xmlns=\"http://tempuri.org/\"><AuthorID>1</AuthorID><Category>MS</Category><Name>數學之美(第二版) </Name><Numberofcopies>12</Numberofcopies><Price>37.99</Price><PublishDate>2009-01-11T00:00:00</PublishDate><Rating>A</Rating></Books>";

            string postResult = client.Post(data, uriPost);
            textBoxMsg.Text = "\r\n\r\n\r\n" + postResult;
        }

 

 

       4) 在visual studio 2015中啟動客戶端應用程序,然后使用鼠標點擊“Rest Post”按鈕,結果如下圖。

 

 

 六、通過瀏覽器來訪問WCF服務

     通過瀏覽器來訪問WCF服務,主要是用jquery實現GET和POST訪問,采用jquery訪問REST服務,消息格式選擇Xml。

      1) 我們在項目目錄下面創建一個testRest.html文件,文件中的內容如下:

<html>
     <head>
         <script src="../../Scripts/jquery-2.2.3.min.js" type="text/javascript"></script>
         <script type="text/javascript">  

 function AjaxGet() {
                  $.ajax({
                     type: "GET",
                     contentType: "text/xml",
                     url: "http://127.0.0.1:8888/Books/Get/5",                  

                     success: function (data) {
                         alert(data);
                         $("#TextGet").val(data);
                     },

   complete:function(XMLHttpRequest,textStatus){
               alert(XMLHttpRequest.responseText);
               alert(textStatus);            

            },

                     error: function (data) {
                         alert(data);
                     }
                 });

 }

             function HttpPost() {
                 var str = "<Books xmlns=\"http://tempuri.org/\"><AuthorID>1</AuthorID><Category>MS</Category>
<Name>math book ver 1 </Name><Numberofcopies>12</Numberofcopies><Price>47.99</Price><PublishDate>2012-01-11T00:00:00</PublishDate>
<Rating>A</Rating></Books>
"; $.ajax({ type: "POST", contentType: "text/xml", // datatype:"xml", url: "http://127.0.0.1:8888/Books/Add", data: str, success: function (data) { alert(data); $("#TextPost").val(data); }, complete:function(XMLHttpRequest,textStatus){ alert(XMLHttpRequest.responseText); alert(textStatus); }, error: function (data) { alert(data); } }); } </script> <style type="text/css"> #TextGet { width: 700px; } #TextPost { width: 700px; } </style> </head> <body> <input id="ButtonGet" type="button" value="GET" onclick="AjaxGet()" /> <input id="TextGet" type="text" /> <p/> <input id="ButtonPost" type="button" value="POST" onclick="HttpPost()" /> <input id="TextPost" type="text" /> </body> </html>

 

     2)使用瀏覽器IE打開testRest.html,然后點擊“ GET” 按鈕,結果如下圖。

 

 

 

  3)使用瀏覽器IE打開testRest.html,然后點擊“ POST” 按鈕,結果如下圖。

 

 

備注:

       在firefox下面,怎么訪問都不成功,都是報405Method not allowed)錯誤信息,在IE下面訪問正常,具體原因沒找到,如果有知道解決方案的,請留言。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM