【www.bbyears.com--WebService】
OK 现在我们来体验webservice
代码如下//server端 serverSoap.php
$soap = new SoapServer(null,array("uri"=>"http://192.168.1.179/"));//This uri is your SERVER ip.
$soap->addFunction("minus_func"); //Register the function
$soap->addFunction(SOAP_FUNCTIONS_ALL);
$soap->handle();
function minus_func($i, $j){
$res = $i - $j;
return $res;
}
//client端 clientSoap.php
try {
$client = new SoapClient(null,
array("location" =>"http://192.168.1.179/test/serverSoap.php","uri" => "http://127.0.0.1/")
);
echo $client->minus_func(100,99);
} catch (SoapFault $fault){
echo "Error: ",$fault->faultcode,", string: ",$fault->faultstring;
}
这是客户端调用服务器端函数的例子,我们再搞个class的。
//server端 serverSoap.php
$classExample = array();
$soap = new SoapServer(null,array("uri"=>"http://192.168.1.179/","classExample"=>$classExample));
$soap->setClass("chesterClass");
$soap->handle();
class chesterClass {
public $name = "Chester";
function getName() {
return $this->name;
}
}
//client端 clientSoap.php
try {
$client = new SoapClient(null,
array("location" =>"http://192.168.1.179/test/serverSoap.php","uri" => "http://127.0.0.1/")
);
echo $client->getName();
} catch (SoapFault $fault){
echo "Error: ",$fault->faultcode,", string: ",$fault->faultstring;
}
以上代码我已经测试通过
代理方式调用
/******************************************************************************/
/* 文件名 : soapclient.php
/* 说 明 : WebService接口客户端例程
/******************************************************************************/
require("NuSoap.php");
//创建一个soapclient对象,参数是server的WSDL
$client=new soapclient("http://localhost/Webservices/Service.asmx?WSDL", "wsdl");
//生成proxy类
$proxy=$client->getProxy();
//调用远程函数
$aryResult=$proxy->login("username",MD5("password"));
//echo $client->debug_str;
/*
if (!$err=$proxy->getError()) {
print_r($aryResult);
} else {
print "ERROR: $err";
}
*/
$document=$proxy->document;
echo <<
$document
SoapDocument;
?>
许多使用NuSoap 调用.NET WebService或J2EE WebService的朋友可能都遇到过中文乱码问题,下面介绍这一问题的出现的原因和相应的解决方法。
NuSoap调用WebService出现乱码的原因:
通常我们进行WebService开发时都是用的UTF-8编码,这时我们需要设置:
代码如下
$client->soap_defencoding = "utf-8";
同时,需要让xml以同样的编码方式传递:
代码如下$client->xml_encoding = "utf-8";
至此应该是一切正常了才对,但是我们在输出结果的时候,却发现返回的是乱码。
NuSoap调用WebService出现乱码的解决方法:
实际上,开启了调试功能的朋友,相信会发现$client->response返回的是正确的结果,为什么$result = $client->call($action, array("parameters" => $param)); 却是乱码呢?
研究过NuSoap代码后我们会发现,当xml_encoding设置为UTF-8时,NuSoap会检测decode_utf8的设置,如果为true,会执行 PHP 里面的utf8_decode函数,而NuSoap默认为true,因此,我们需要设置:
代码如下$client->soap_defencoding = "utf-8";
$client->decode_utf8 = false;
$client->xml_encoding = "utf-8";