WebService學習系列(三)------XML-RPC

一、啥是XML-RPC

      XML-RPC可以理解爲簡化版的soap,對數據的包裝相對簡潔。

二、配置

   打開php.ini擴展,打開以下擴展,配置完重啓Apache。

  

  

三、構建服務

1.新建rpc-server.php    rpc服務端

<?php
function hello(){
	return 'hhahaha';
}
//創建RPC服務器
$server=xmlrpc_server_create();
//把用戶寫的函數註冊到RPC服務器中
xmlrpc_server_register_method($server,'hello','hello');
//收取POST請求(內容是XML格式)
$request=$HTTP_RAW_POST_DATA;
//調用相關的方法
$response=xmlrpc_server_call_method($server,$request,null);
//輸出
header('content-type:text/xml');
echo $response;
xml_server_destroy($server);
?>
2.新建rpc-client.php

封裝自己的rpc-client請求類

class rpcclient{
	protected $url;
	public function __construct($url){
	 
		$this->url=$url;
	}
	protected function __query($request){
		$context=stream_context_create(
				array(
					'http'=>array(
						'method'=>'POST',
						'header'=>'Content-Type:text/xml',
						'content'=>$request
					)
				)
		);
		$xml=file_get_contents($this->url,false,$context);
		//var_dump($xml);
		return xmlrpc_decode($xml);
	}
	//遇到未定義的方法時,此方法未被調用
	public function __call($method,$args){
		$request=xmlrpc_encode_request($method,$args);
		return $this->__query($request);
	}
}


2.手寫HTTP協議,看返回結果。

POST /webservice/rpc-server.php HTTP/1.1
Host:localhost
Content-type:textdomain/xml
content-length:260

<?xml version="1.0" encoding="iso-8859-1"?>
<methodCall>
<methodName>hello</methodName>
<params>
<param>
<value>
<string>zhong</string>
</value>
</param>
<param>
<value>
<string>guo</string>
</value>
</param>
</params>
</methodCall>

返回結果:

3.服務端增加代碼

<?php
function hello(){
	return 'hhahaha';
}
/*
 *注意,rpc服務器在調用函數時,傳的參數是這樣的
 array(0=>'函數名',1=>array(實參1,實參2,...實參N),2=>NULL);
 * */
function sum($method,$args,$extra){
	return array_sum($args);
}
//創建RPC服務器
$server=xmlrpc_server_create();
//把用戶寫的函數註冊到RPC服務器中
xmlrpc_server_register_method($server,'hello','hello');
xmlrpc_server_register_method($server,'sum','sum');
//收取POST請求(內容是XML格式)
$request=$HTTP_RAW_POST_DATA;
//調用相關的方法
$response=xmlrpc_server_call_method($server,$request,null);
//輸出
header('Content-Type:text/xml');
echo $response;
xmlrpc_server_destroy($server);
?>


4.客戶端調用服務端

 

$client=new rpcclient('http://localhost/webservice/rpc-server.php');
echo $client->hello('aa','bb');
print_r($client->sum(4,5,6));


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章