WCF learning journey-Support for REST client applications (24), wcfrest

Source: Internet
Author: User
Tags baseuri

WCF learning journey-Support for REST client applications (24), wcfrest
WCF learning journey-implementing the REST Service (22)
How to Implement RestFul server applications (23): In the last two articles, I briefly introduced the methods provided by RestFul and WCF to support RestFul, and create a REST-supported WCF server program. This article describes how to call the RestFul server described in the previous article. 5. Windows client call

To emphasize the versatility of REST, the client does not need to call the service in the form of WCF, but uses HttpWebResponse for direct access through programming. The message format is XML.

First, we use C # To encapsulate a RestHelper class to implement http get and POST request methods. The Code is as follows.

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> /// constructor /// </summary> /// <param name = "baseUrl"> </param> public RestHelper (string baseUri) {this. baseUri = baseUri;} // <summary> // base address // </summary> private string BaseUri; /// <summary> /// Post call // </summary> /// <param name = "data"> </param> /// <param name = "uri"> </param> // <returns> </returns> public string Post (string data, string uri) {// Web access object string serviceUrl = string. format ("{0}/{1}", this. baseUri, uri); HttpWebRequest myRequest = (HttpWebRequest) WebRequest. create (serviceUrl); // convert to a network stream byte [] buf = UnicodeEncoding. UTF8.GetBytes (data); // sets myRequest. method = "POST"; myRequest. contentLength = buf. length; myRequest. contentType = "text/html"; // send the request Stream newStream = myRequest. getRequestStream (); newStream. write (buf, 0, buf. length); newStream. close (); // get the interface return value 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 call /// </summary> /// <param name = "uri"> </param> /// <returns> </returns> public string Get (string uri) {// Web access object string serviceUrl = string. format ("{0}/{1}", this. baseUri, uri); HttpWebRequest myRequest = (HttpWebRequest) WebRequest. create (serviceUrl); // obtain the interface return value 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 ;}}}

 

Next, let's implement the main function, call two interfaces in order, and display the return value. Pay attention to the namespace specified in XML.

In visual studio 2015, create a Windows form named Form1. Put two buttons in Form1: "Rest Get" and "Rest Post ".

1) Implement the Get method in the "Rest Get" button. The Code is as follows:

 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) Start the client application in visual studio 2015, and click "Rest Get" with the mouse. The result is shown in.

 

 

3) Implement the Post method in the "Rest Post" button. The Code is as follows:

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> beauty of Mathematics (Second Edition) </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" + postResult ;}

 

 

4) Start the client application in visual studio 2015, and click "Rest Post" with the mouse. The result is shown in.

 

 

  6. Access the WCF Service through a browser

Access the WCF Service through a browser, mainly through GET and POST access using jquery, access the REST service using jquery, and select Xml as the message format.

1) create a testrest.html file under the project directory. The content of the file is as follows:

<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>

 

2. Open testrest.html with the browser ieand click "GET". The result is shown in.

 

 

 

3rd, open testrest.html with the browser ieand click "POST". The result is shown in.

 

 

Note:

In firefox, when access fails, the error 405 (Method not allowed) is reported. The access is normal in IE. The specific cause is not found. If you know the solution, leave a message.

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.