VB.net 2010 视频教程 VB.net 2010 视频教程 python基础视频教程
SQL Server 2008 视频教程 c#入门经典教程 Visual Basic从门到精通视频教程
当前位置:
首页 > temp > C#教程 >
  • WCF学习之旅—实现支持REST客户端应用(二十四)

 

五、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下面访问正常,具体原因没找到,如果有知道解决方案的,请留言。

 

出处:https://www.cnblogs.com/chillsrc/p/5874703.html

 



相关教程