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 { ////// 构造函数 /// /// public RestHelper(string baseUri) { this.BaseUri = baseUri; } /// /// 基地址 /// private string BaseUri; /// /// Post调用 /// /// /// /// 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; } /// /// Get调用 /// /// /// 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 = ""; string postResult = client.Post(data, uriPost); textBoxMsg.Text = "\r\n\r\n\r\n" + postResult; } 1 MS 数学之美(第二版) 12 37.99 2009-01-11T00:00:00 A
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 = ""; $.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> 1 MS math book ver 1 12 47.99 2012-01-11T00:00:00 A
2)使用浏览器IE打开testRest.html,然后点击“ GET” 按钮,结果如下图。
3)使用浏览器IE打开testRest.html,然后点击“ POST” 按钮,结果如下图。
备注:
在firefox下面,怎么访问都不成功,都是报405(Method not allowed)错误信息,在IE下面访问正常,具体原因没找到,如果有知道解决方案的,请留言。