Practice REST-based Webservice (PHP, C #)

Source: Internet
Author: User
Tags representational state transfer

Concept:

The style of WEB Services. I checked it from Wikipedia. There are no more than a dozen, but REST and RPC are commonly used. Among them, the SOAP-based Webservice is RPC-style.

The full name of REST is Representational State Transfer. It is a stateless, cs-structured, and cacheable communication protocol. In fact, it uses the HTTP protocol. From some points of view, the Internet itself is based on HTTP, so it can also be considered as a REST-style Webservice. REST-style Webservice is lightweight for SOAP, a protocol that competes with SOAP. The request is also relatively simple. For example, a SOAP-based Webservice request may be an XML file containing redundant information:

<? Xml version = "1.0"?>

<Soap: Envelope

Xmlns: soap = "http://www.w3.org/2001/12/soap-envelope"

Soap: encodingStyle = "http://www.w3.org/2001/12/soap-encoding">

<Soap: body pb = "http://www.acme.com/phonebook">

<Pb: GetUserDetails>

<Pb: UserID> 12345 </pb: UserID>

</Pb: GetUserDetails>

</Soap: Body>

</Soap: Envelope>

The REST request is simple, but it is only a URL address: http://www.acme.com/phonebook/userdetails/12345. Only a browser can verify that this restful webserviceworkflow is normal. HTTP request methods include GET, POST, PUT, PATCH, and DELETE. REST can also use these request methods. The REST Webservice usually responds to an XML file, but unlike SOAP, REST does not necessarily need to respond to the returned XML file. It can also be in CSV or Json format.

Many companies adopt REST-style WebServices, such as Google Glass API, Twitter, Yahoo, Flickr, and Amazon. For example, Google has a Webservice, Google Maps API, which provides two output formats: JSON and XML. Are addresses http://maps.googleapis.com/maps/api/geocode/json? Parameters and http://maps.googleapis.com/maps/api/geocode/xml? Parameters

The specific use of the service and parameters can be found in the https://developers.google.com/maps/documentation/geocoding? Hl = zh-CN & csw = 1 # XML

Demo:

The following shows a REST-style webservice developed based on the PHP language.

<?phpswitch($_SERVER['REQUEST_METHOD']){    case 'GET':        $id=$_GET["id"];        $arrayid = explode(",", $id);        search($arrayid);        break;    case 'POST':        $id=$_POST["id"];        $username=$_POST["username"];        $sex=$_POST["sex"];        $age=$_POST["age"];                                              add($id,$username,$sex,$age);        break;    default:        exit();}function search($arrayid){    $users=getCsvFile("example.csv");    $string="";    foreach($users as $a)    {        $id=$a[0];        if(in_array($id,$arrayid))        {            $string.= <<<EOF    <user id="$a[0]">        <name>$a[1]</name>        <sex>$a[2]</sex>        <age>$a[3]</age>    </user>EOF;        }    }    $string="<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n"            ."<data>\r\n"            .$string            ."</data>";                                      header("Content-type:application/xml");    print($string);                                  }function add($id,$username,$sex,$age){    $users=getCsvFile("example.csv");    $string="$id,$username,$sex,$age";                                      WriteLinetxt($string,"example.csv");                                      $string="<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n"            ."<return>\r\n"            ."  <status>0</status>\r\n"            ."</return>\r\n";                                      header("Content-type:application/xml");    print($string);                                  }function getCsvFile($filepath)    {        $handle=null;        $returnvalue=array();        try        {            $handle = fopen($filepath,"r");            while ($data = fgetcsv($handle, 1000, ","))            {                array_push($returnvalue,$data);            }            fclose($handle);        }        catch(Exception $e)        {            fclose($handle);            $handle=null;            die("Error!: ".$e->getMessage()."<br/>");        }                                              return $returnvalue;    }function WriteLinetxt($content,$filename){        file_put_contents($filename, $content."\r\n",FILE_APPEND);}?>

Code Description:

The above code is used to identify whether the request is POST or GET. If it is GET, the query ID must be included. The service returns an xm document whose Content-type is application/xml. If it is POST, the corresponding POST value will be written to the database.

In this example, the database simply uses CSV files, that is, text files that use commas to separate data. The data file is as follows:

650) this. width = 650; "style =" border-bottom: 0px; border-left: 0px; border-top: 0px; border-right: 0px "title =" CBD247FF7AF9473193DC06EB24DBCCC8 "border =" 0 "alt =" CBD247FF7AF9473193DC06EB24DBCCC8 "src =" http://www.bkjia.com/uploads/allimg/131228/1124314622-0.jpg "height =" 169 "/>

Since REST-style web services can be verified through a browser, you can enter a url for testing. In this example, url rewriting is not used. If url rewriting is used, the service address is more friendly.

650) this. width = 650; "style =" border-bottom: 0px; border-left: 0px; border-top: 0px; border-right: 0px "title =" D87BE31CF24D416BA901BA11EF15A2A6 "border =" 0 "alt =" D87BE31CF24D416BA901BA11EF15A2A6 "src =" http://www.bkjia.com/uploads/allimg/131228/1124312N4-1.jpg "height =" 431 "/>

After the service is deployed, you can call it. In PHP, you can use simplexml_load_file to get the xml file.

<?php$url="http://localhost:8080/b.php?id=1001,1003,1004";$response=simplexml_load_file($url);var_dump($response);?>

650) this. width = 650; "style =" border-bottom: 0px; border-left: 0px; border-top: 0px; border-right: 0px "title =" inline "border =" 0 "alt =" 74A2BDE9531F4A879C284A805D575126 "src =" http://www.bkjia.com/uploads/allimg/131228/1124313A5-2.jpg "height =" 536 "/>

Through var_dump, we can see that the obtained object is a SimpleXMLElement directly. Of course, you can also convert it to a string object.

The following php code is used to simulate POST data. PHP commonly uses three methods to simulate POST actions: Curl, socket, and file_get_contents. The file_get_contents method is used here. The Code is as follows:

<? Php $ url = "http: // localhost: 8080/B. php "; $ data = array ('id' => '2013', 'username' => 'zhang', 'sex' => 'male ', 'age' => '20'); $ post_string = http_build_query ($ data); $ context = array ('http' => array ('method' => 'post ', 'header' => 'content-type: application/x-www-form-urlencoded', 'content' => $ post_string); $ stream_context = stream_context_create ($ context ); $ response = file_get_contents ($ url, false, $ stream_cont Ext); $ xml = simplexml_load_string ($ response); var_dump ($ xml);?>

In the code, simulate POST submission, obtain the returned string, and convert the string to the SimpleXMLElement object. Data in the database has also been written.

650) this. width = 650; "style =" border-bottom: 0px; border-left: 0px; border-top: 0px; border-right: 0px "title =" 5ABB6024DDF8491FAE0A051F8E524C15 "border =" 0 "alt =" 5ABB6024DDF8491FAE0A051F8E524C15 "src =" http://www.bkjia.com/uploads/allimg/131228/1124315293-3.jpg "height =" 127 "/>

C # version access:

C # You can also use code to call a REST-style Webservice written in PHP. The Code is as follows:

Class Program {static void Main (string [] args) {string [] paramName = {"id"}; string [] paramVal = {"1001,1004 "}; var p = HttpGet ("http: // localhost: 8080/B. php ", paramName, paramVal); Console. writeLine (p); Console. writeLine ("-----------------------------"); string [] paramName1 = {"id", "username", "sex", "age"}; string [] paramVal1 = {"1030 ", "tom", "male", "23"}; var p1 = HttpPost ("http: // loc Alhost: 8080/B. php ", paramName1, paramVal1); Console. writeLine (p1);} static string HttpGet (string url, string [] paramName, string [] paramVal) {StringBuilder paramz = new StringBuilder (); for (int I = 0; I <paramName. length; I ++) {paramz. append (paramName [I]); paramz. append ("="); paramz. append (HttpUtility. urlEncode (paramVal [I]); paramz. append ("&") ;}url + = "? "+ Paramz. toString (); HttpWebRequest req = WebRequest. create (url) as HttpWebRequest; string result = null; using (HttpWebResponse resp = req. getResponse () as HttpWebResponse) {StreamReader reader = new StreamReader (resp. getResponseStream (); result = reader. readToEnd ();} return result;} static string HttpPost (string url, string [] paramName, string [] paramVal) {HttpWebRequest req = WebRequest. create (new Uri (url) as HttpWebRequest; req. method = "POST"; req. contentType = "application/x-www-form-urlencoded"; // Build a string with all the params, properly encoded. // We assume that the arrays paramName and paramVal are // of equal length: StringBuilder paramz = new StringBuilder (); for (int I = 0; I <paramName. length; I ++) {paramz. append (paramName [I]); paramz. append ("="); paramz. append (HttpUtility. urlEncode (paramVal [I]); paramz. append ("&") ;}// Encode the parameters as form data: byte [] formData = UTF8Encoding. UTF8.GetBytes (paramz. toString (); req. contentLength = formData. length; // Send the request: using (Stream post = req. getRequestStream () {post. write (formData, 0, formData. length);} // Pick up the response: string result = null; using (HttpWebResponse resp = req. getResponse () as HttpWebResponse) {StreamReader reader = new StreamReader (resp. getResponseStream (); result = reader. readToEnd () ;}return result ;}}

650) this. width = 650; "style =" border-bottom: 0px; border-left: 0px; border-top: 0px; border-right: 0px "title =" F8FED7F3BB7C4808801FE1FA3AC1C220 "border =" 0 "alt =" F8FED7F3BB7C4808801FE1FA3AC1C220 "src =" http://www.bkjia.com/uploads/allimg/131228/1124314302-4.jpg "height =" 335 "/>

Reference:

Http://geeknizer.com/rest-vs-soap-using-http-choosing-the-right-webservice-protocol/

Http://msdn.microsoft.com/zh-cn/magazine/dd942839.aspx

Http://www.gen-x-design.com/archives/create-a-rest-api-with-php/

Http://rest.elkstein.org/2008/02/what-is-rest.html

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.