星空网 > 软件开发 > ASP.net

WCF学习之旅—实现支持REST客户端应用(二十四)

            WCF学习之旅—实现REST服务(二十二)

           WCF学习之旅—实现支持REST服务端应用(二十三)

          在上二篇文章中简单介绍了一下RestFul与WCF支持RestFul所提供的方法,及创建一个支持REST的WCF服务端程序,本文介绍如何调用上一篇文章介绍的RestFul服务端。

 

五、Windows客户端调用

          为了强调REST的通用性,客户端不用WCF的形式调用服务,而是采用HttpWebResponse通过编程方式直接访问,消息格式我们选

         首先,我们使用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 Return HttpUtility.HtmlDecode(reader.ReadToEnd());        reader.Close();        myResponse.Close();        return Return/// <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 Return HttpUtility.UrlDecode(reader.ReadToEnd());       reader.Close();      myResponse.Close();      return Return

 

         其次,我们来实现主函数,按顺序调用两个接口,并显示返回值。需要注意

         我们在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”按钮,结果如下图。

 WCF学习之旅—实现支持REST客户端应用(二十四)

 

          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 ";      string postResult = client.Post(data, uriPost);      textBoxMsg.Text = "\r\n\r\n\r\n" + postResult;    }

 

 

       4) 在visual studio 2015中启动客户端应用程序,然后使用鼠标点击“Rest Post”按钮,结果如下图。

 WCF学习之旅—实现支持REST客户端应用(二十四)

 

 六、通过浏览器来访问WCF服务

     通过浏览器来访问WCF服务,主要是用jquery实现GET和POST访问,采用jquery访问REST服务,消息格式选择

      1) 我们在项目目录下面创建一个testRest.html文件,文件中的内容如下:

<html>   <head>     <script src='/images/loading.gif' data-original="../../Scripts/jquery-2.2.3.min.js" type="text/javascript"></script>     <script type="text/javascript">  function AjaxGet() {         $.ajax({           type: "GET",           contentType: "text/",           url: "http://127.0.0.1:8888/Books/Get/5",                    success: function (data) {             alert(data);             $("#TextGet").val(data);           },  complete:function(function (data) {             alert(data);           }         }); }       function HttpPost() {         var str = "<Books <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/",// datatype:" url: "http://127.0.0.1:8888/Books/Add", data: str, success: function (data) { alert(data); $("#TextPost").val(data); }, complete:function(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” 按钮,结果如下图。

 WCF学习之旅—实现支持REST客户端应用(二十四)

 

 

  3)使用浏览器IE打开testRest.html,然后点击“ POST” 按钮,结果如下图。

 WCF学习之旅—实现支持REST客户端应用(二十四)

 

备注:

       在firefox下面,怎么访问都不成功,都是报405(Method not allowed)错误信息,在IE下面访问正常,具体原因没找到,如果有知道解决方案的,请留言。

 




原标题:WCF学习之旅—实现支持REST客户端应用(二十四)

关键词:wcf

wcf
*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们: admin#shaoqun.com (#换成@)。

重磅!亚马逊商品合规审查来袭,大量Listing将被下架...:https://www.ikjzd.com/articles/130551
个人创业还能不能做亚马逊?:https://www.ikjzd.com/articles/130552
互联网+跨境电商平台斯达领科完成3亿A轮融资:https://www.ikjzd.com/articles/130553
大量卖家拿到亚马逊赔款!你竟然还不知道?:https://www.ikjzd.com/articles/130555
跨境电商如何选择物流:https://www.ikjzd.com/articles/130556
亚马逊站外爆款打造四部曲:送你“秋天的第一个爆款”:https://www.ikjzd.com/articles/130557
云南抚仙湖旅游攻略更佳行程安排,景点攻略大全:https://www.vstour.cn/a/408242.html
珠海附近过年旅游景点 珠海附近过年旅游景点免费:https://www.vstour.cn/a/408243.html
相关文章
我的浏览记录
最新相关资讯
海外公司注册 | 跨境电商服务平台 | 深圳旅行社 | 东南亚物流