当前位置: 澳门新濠3559 > 编程 > 正文

2 WebService 实现主要步骤,而我方使用php

时间:2019-12-08 22:39来源:编程
从前一阵开始,公司要和对方做webservice对接。由于对方使用.net语言,而我方使用php。本来经理是要求我们也用.net写webservice的服务端。而我上学时学的.net全忘了。。。 作为开发者来讲

从前一阵开始,公司要和对方做web service对接。由于对方使用.net语言,而我方使用php。本来经理是要求我们也用.net写web service的服务端。而我上学时学的.net全忘了。。。

作为开发者来讲,要想写webservice接口或者调用别人的webservice接口,首先需要了解什么是webservice。简单说, WebService就是一些站点开放一些服务出来, 也可以是你自己开发的Service, 也就是一些方法, 通过URL,指定某一个方法名,发出请求,站点里的这个服务(方法),接到你的请求,根据传过来的参数,做一些处理,然后把处理后的结果以XML形式返回来给你,你的程序就解析这些XML数据,然后显示出来或做其它操作。

结合SoapDiscovery实现简单的WebService服务

于是开始上网搜索用可否直接用php进行编程。

写webservice需要了解:基础的 Web Services 平台是 XML + HTTP;另外Web services 平台的元素:SOAP (简易对象访问协议),UDDI (通用描述、发现及整合),WSDL (Web services 描述语言);任何webservice都包括客户端和服务端。下面以实例讲解如何用php写webservice接口让别人调用:

1 修改php.ini文件

修改php.ini  ;extension=php_soap.dll

首先需要建一个.wsdl文件,那么php如何建这个文件呢。有两种方式可以实现,一种是直接用zend studio工具生成;另一种就是php根据SoapDiscovery.class.php自动生成wsdl文件;具体哪一种根据自己情况选择,我一般用的是前者这样比较快速。下面写一下用类如何生成wsdl文件,首先需要上网上下载那个类文件,然后引入类文件后,看如下代码:
creat_wsdl.php

  php_soap.dll 

那么首先写一个简单的服务端的测试方法

复制代码 代码如下:

  extension=php_soap.dll

class Service {
    public function HelloWorld() {
        return "Hello";
    }
}

<?php
include_once('Service.php');
include_once('SoapDiscovery.class.php');
$wsdl=new SoapDiscovery('Service','soap');//第一参数为类名,也是生成wsdl的文件名Service.wsdl,第二个参数是服务的名字可以随便写
$wsdl->getWSDL();
?>

2 WebService 实现主要步骤

把这个方法存为一个php文件,一个web service文件就做好了。

这样运行creat_wsdl.php文件就可以生成wsdl文件了。是不是很简单
任何一个webservice都需要和一个实现类绑定的。也就是说别人调用的wsdl文件其实真正其作用的就是实现类中的方法;如下代码为服务端类文件
Service.php

  • 生成wsdl描述文件
  • 使用SoapServer注册服务
  • 使用SoapClient调用服务

由于web service需要一个xml格式的wsdl文件来进行对方法进行解析。所以我们也需要一个wsdl文件,.net比较方便可以自动生成,php就得自己写了,不过,网上有已经造好的轮子,我们直接拿来调用就好了。

复制代码 代码如下:

3 目录结构以及代码 

澳门新濠3559 1澳门新濠3559 2

2 WebService 实现主要步骤,而我方使用php。<?php
class Service
{
public function Hello()
{
echo 'hello good';
}
public function Add($a,$b)
{
return $a+$b;
}
}
$server=SoapServer('Service.php',array('soap_version'=>soap_1_2));
$server->setClass('Service');//注册Service类的所有方法
$server->handle();//处理请求
?>

   根目录

<?php

/**
 * Copyright (c) 2005, Braulio Jos?Solano Rojas
 * All rights reserved.
 * 
 * Redistribution and use in source and binary forms, with or without modification, are
 * permitted provided that the following conditions are met:
 * 
 *     Redistributions of source code must retain the above copyright notice, this list of
 *     conditions and the following disclaimer. 
 *     Redistributions in binary form must reproduce the above copyright notice, this list of
 *     conditions and the following disclaimer in the documentation and/or other materials
 *     provided with the distribution. 
 *     Neither the name of the Solsoft de Costa Rica S.A. nor the names of its contributors may
 *     be used to endorse or promote products derived from this software without specific
 *     prior written permission.
 * 
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
 * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
 * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
 * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
 * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 * 
 *
 * @version $Id$
 * @copyright 2005 
 */

/**
 * SoapDiscovery Class that provides Web Service Definition Language (WSDL).
 * 
 * @package SoapDiscovery
 * @author Braulio Jos?Solano Rojas
 * @copyright Copyright (c) 2005 Braulio Jos?Solano Rojas
 * @version $Id$
 * @access public
 * */
class SoapDiscovery {

    private $class_name = '';
    private $service_name = '';

    /**
     * SoapDiscovery::__construct() SoapDiscovery class Constructor.
     * 
     * @param string $class_name
     * @param string $service_name
     * */
    public function __construct($class_name = '', $service_name = '') {
        $this->class_name = $class_name;
        $this->service_name = $service_name;
    }

    /**
     * SoapDiscovery::getWSDL() Returns the WSDL of a class if the class is instantiable.
     * 
     * @return string
     * */
    public function getWSDL() {
        if (empty($this->service_name)) {
            throw new Exception('No service name.');
        }
        $headerWSDL = "<?xml version="1.0" ?>n";
        $headerWSDL.= "<definitions name="$this->service_name" targetNamespace="urn:$this->service_name" xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:tns="urn:$this->service_name" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/" xmlns="http://schemas.xmlsoap.org/wsdl/">n";
        $headerWSDL.= "<types xmlns="http://schemas.xmlsoap.org/wsdl/" />n";

        if (empty($this->class_name)) {
            throw new Exception('No class name.');
        }

        $class = new ReflectionClass($this->class_name);

        if (!$class->isInstantiable()) {
            throw new Exception('Class is not instantiable.');
        }

        $methods = $class->getMethods();

        $portTypeWSDL = '<portType name="' . $this->service_name . 'Port">';
        $bindingWSDL = '<binding name="' . $this->service_name . 'Binding" type="tns:' . $this->service_name . "Port">n<soap:binding style="rpc" transport="http://schemas.xmlsoap.org/soap/http" />n";
        $serviceWSDL = '<service name="' . $this->service_name . "">n<documentation />n<port name="" . $this->service_name . 'Port" binding="tns:' . $this->service_name . "Binding"><soap:address location="http://" . $_SERVER['SERVER_NAME'] . ':' . $_SERVER['SERVER_PORT'] . $_SERVER['PHP_SELF'] . "" />n</port>n</service>n";
        $messageWSDL = '';
        foreach ($methods as $method) {
            if ($method->isPublic() && !$method->isConstructor()) {
                $portTypeWSDL.= '<operation name="' . $method->getName() . "">n" . '<input message="tns:' . $method->getName() . "Request" />n<output message="tns:" . $method->getName() . "Response" />n</operation>n";
                $bindingWSDL.= '<operation name="' . $method->getName() . "">n" . '<soap:operation soapAction="urn:' . $this->service_name . '#' . $this->class_name . '#' . $method->getName() . "" />n<input><soap:body use="encoded" namespace="urn:$this->service_name" encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" />n</input>n<output>n<soap:body use="encoded" namespace="urn:$this->service_name" encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" />n</output>n</operation>n";
                $messageWSDL.= '<message name="' . $method->getName() . "Request">n";
                $parameters = $method->getParameters();
                foreach ($parameters as $parameter) {
                    $messageWSDL.= '<part name="' . $parameter->getName() . "" type="xsd:string" />n";
                }
                $messageWSDL.= "</message>n";
                $messageWSDL.= '<message name="' . $method->getName() . "Response">n";
                $messageWSDL.= '<part name="' . $method->getName() . "" type="xsd:string" />n";
                $messageWSDL.= "</message>n";
            }
        }
        $portTypeWSDL.= "</portType>n";
        $bindingWSDL.= "</binding>n";
        //return sprintf('%s%s%s%s%s%s', $headerWSDL, $portTypeWSDL, $bindingWSDL, $serviceWSDL, $messageWSDL, '</definitions>');
        //生成wsdl文件,将上面的return注释
        $fso = fopen($this->class_name . ".wsdl", "w");
        fwrite($fso, sprintf('%s%s%s%s%s%s', $headerWSDL, $portTypeWSDL, $bindingWSDL, $serviceWSDL, $messageWSDL, '</definitions>'));
    }

    /**
     * SoapDiscovery::getDiscovery() Returns discovery of WSDL.
     * 
     * @return string
     * */
    public function getDiscovery() {
        return "<?xml version="1.0" ?>n<disco:discovery xmlns:disco="http://schemas.xmlsoap.org/disco/" xmlns:scl="http://schemas.xmlsoap.org/disco/scl/">n<scl:contractRef ref="http://" . $_SERVER['SERVER_NAME'] . ':' . $_SERVER['SERVER_PORT'] . $_SERVER['PHP_SELF'] . "?wsdl" />n</disco:discovery>";
    }

}

?>

写好服务端和wsdl文件后那么就需要客户端调用了。请看客户端调用代码:

  ==service目录

SoapDiscovery.class.php

client.php

  ||== SoapDiscovery.php 【Soap wsdl文件生成类 】

把上面这段代码也存为一个php文件,作为wsdl的制造方法。

复制代码 代码如下:

  ||==SoapService.php 【web service 提供的列表】

<?php

include("Service.php");
include("SoapDiscovery.class.php");

$disco = new SoapDiscovery('Service', 'Service'); //第一个参数是类名(生成的wsdl文件就是以它来命名的),即Service类,第二个参数是服务的名字(这个可以随便写)。
$disco->getWSDL();

<?php
ini_set('soap.wsdl_cache_enabled','0');//缓存
$soap=new SoapClient('');
echo $soap->Add(1,2);
//echo $soap->_soapCall('Add',array(1,2))//或者这样调用也可以
?>

  ==controllers目录

最后,运行上面这段代码就可以生成一个wsdl文件了。不过,new SoapDiscovery时的第二个参数要注意了,这个名字是service的服务名,php调用的时候用不到,但是如果你的web service是写给.net的同学调用的话,那么这个名字要跟对方约定好。因为.net方面会使用这个名字当做类名来调用我们的方法。

这就是一个完整的写webservice接口和调用的实例代码,希望对需要的phper有所帮助;
那么调用别人的webservice接口就是client.php所写的代码这样调用。

  ||==CreatewsController.php 【生成WSDL文件 】

现在,wsdl文件也生成了。这时,我们需要在最开始写的服务方法里加上一段代码。

  ||==ServiceController【注册、调用测试】

<?php
class Service {
    public function HelloWorld() {
        return "Hello";
    }



$server = new SoapServer('Service.wsdl', array('soap_version' => SOAP_1_2));
$server->setClass("Service"); //注册Service类的所有方法 
$server->handle(); //处理请求
?>

SoapDiscovery.php 【Soap wsdl文件生成类 】

澳门新濠3559 3澳门新濠3559 4

<?php
/**
 * Created by PhpStorm.
 * User: 知电
 * Date: 2018-1-2
 * Time: 10:14
 */
namespace appservice;
/**
 * Copyright (c) 2005, Braulio Jos?Solano Rojas
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without modification, are
 * permitted provided that the following conditions are met:
 *
 *     Redistributions of source code must retain the above copyright notice, this list of
 *     conditions and the following disclaimer.
 *     Redistributions in binary form must reproduce the above copyright notice, this list of
 *     conditions and the following disclaimer in the documentation and/or other materials
 *     provided with the distribution.
 *     Neither the name of the Solsoft de Costa Rica S.A. nor the names of its contributors may
 *     be used to endorse or promote products derived from this software without specific
 *     prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
 * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
 * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
 * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
 * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 *
 * @version $Id$
 * @copyright 2005
 */

/**
 * SoapDiscovery Class that provides Web Service Definition Language (WSDL).
 *
 * @package SoapDiscovery
 * @author Braulio Jos?Solano Rojas
 * @copyright Copyright (c) 2005 Braulio Jos?Solano Rojas
 * @version $Id$
 * @access public
 * */
class SoapDiscovery
{

    private $class_name = '';
    private $service_name = '';

    /**
     * SoapDiscovery::__construct() SoapDiscovery class Constructor.
     *
     * @param string $class_name
     * @param string $service_name
     * */
    public function __construct($class_name = '', $service_name = '') {
        $this->class_name = $class_name;
        $this->service_name = $service_name;
    }

    /**
     * SoapDiscovery::getWSDL() Returns the WSDL of a class if the class is instantiable.
     *
     * @return string
     * */
    public function getWSDL() {
        if (empty($this->service_name)) {
            throw new Exception('No service name.');
        }
        $headerWSDL = "<?xml version="1.0" ?>n";
        $headerWSDL.= "<definitions name="$this->service_name" targetNamespace="urn:$this->service_name" xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:tns="urn:$this->service_name" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/" xmlns="http://schemas.xmlsoap.org/wsdl/">n";
        $headerWSDL.= "<types xmlns="http://schemas.xmlsoap.org/wsdl/" />n";

        if (empty($this->class_name)) {
            throw new Exception('No class name.');
        }

        $class = new ReflectionClass($this->class_name);

        if (!$class->isInstantiable()) {
            throw new Exception('Class is not instantiable.');
        }

        $methods = $class->getMethods();

        $portTypeWSDL = '<portType name="' . $this->service_name . 'Port">';
        $bindingWSDL = '<binding name="' . $this->service_name . 'Binding" type="tns:' . $this->service_name . "Port">n<soap:binding style="rpc" transport="http://schemas.xmlsoap.org/soap/http" />n";
        $serviceWSDL = '<service name="' . $this->service_name . "">n<documentation />n<port name="" . $this->service_name . 'Port" binding="tns:' . $this->service_name . "Binding"><soap:address location="http://" . $_SERVER['SERVER_NAME'] . ':' . $_SERVER['SERVER_PORT'] . $_SERVER['PHP_SELF'] . "" />n</port>n</service>n";
        $messageWSDL = '';
        foreach ($methods as $method) {
            if ($method->isPublic() && !$method->isConstructor()) {
                $portTypeWSDL.= '<operation name="' . $method->getName() . "">n" . '<input message="tns:' . $method->getName() . "Request" />n<output message="tns:" . $method->getName() . "Response" />n</operation>n";
                $bindingWSDL.= '<operation name="' . $method->getName() . "">n" . '<soap:operation soapAction="urn:' . $this->service_name . '#' . $this->class_name . '#' . $method->getName() . "" />n<input><soap:body use="encoded" namespace="urn:$this->service_name" encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" />n</input>n<output>n<soap:body use="encoded" namespace="urn:$this->service_name" encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" />n</output>n</operation>n";
                $messageWSDL.= '<message name="' . $method->getName() . "Request">n";
                $parameters = $method->getParameters();
                foreach ($parameters as $parameter) {
                    $messageWSDL.= '<part name="' . $parameter->getName() . "" type="xsd:string" />n";
                }
                $messageWSDL.= "</message>n";
                $messageWSDL.= '<message name="' . $method->getName() . "Response">n";
                $messageWSDL.= '<part name="' . $method->getName() . "" type="xsd:string" />n";
                $messageWSDL.= "</message>n";
            }
        }
        $portTypeWSDL.= "</portType>n";
        $bindingWSDL.= "</binding>n";
        //return sprintf('%s%s%s%s%s%s', $headerWSDL, $portTypeWSDL, $bindingWSDL, $serviceWSDL, $messageWSDL, '</definitions>');
        //生成wsdl文件,将上面的return注释
        $fso = fopen(dirname(__FILE__) . '/' . $this->class_name . ".wsdl", "w111");
        fwrite($fso, sprintf('%s%s%s%s%s%s', $headerWSDL, $portTypeWSDL, $bindingWSDL, $serviceWSDL, $messageWSDL, '</definitions>'));
    }

    /**
     * SoapDiscovery::getDiscovery() Returns discovery of WSDL.
     *
     * @return string
     * */
    public function getDiscovery() {
        return "<?xml version="1.0" ?>n<disco:discovery xmlns:disco="http://schemas.xmlsoap.org/disco/" xmlns:scl="http://schemas.xmlsoap.org/disco/scl/">n<scl:contractRef ref="http://" . $_SERVER['SERVER_NAME'] . ':' . $_SERVER['SERVER_PORT'] . $_SERVER['PHP_SELF'] . "?wsdl" />n</disco:discovery>";
    }
}

View Code

变成如上所示。到这里,我们web service的服务端就完成了。服务端文件的地址就是

SoapService.php 【web service 提供的列表】

澳门新濠3559 5澳门新濠3559 6

<?php
/**
 * Created by PhpStorm.
 * User: 知电
 * Date: 2018-1-2
 * Time: 10:14
 */
namespace appservice;

class SoapService
{
    public function HelloWorld() {
        return "Hello";
    }

    public function Add($a, $b) {
        return $a + $b;
    }

    public function SayHello($name){
        return 'Hell,'. $name;
    }
}

View Code

接下来,创建一个客户端的文件。这里就不用刚刚写的方法了,用网上一个天气预报的web servcie 

CreatewsController.php 【生成WSDL文件 】

澳门新濠3559 7澳门新濠3559 8

<?php

namespace appcontrollers;

use Yii;
use yiiwebController;
use appserviceSoapService;
use appserviceSoapDiscovery;

class CreatewsController extends Controller
{
    public function actionIndex()
    {
        $disco = new SoapDiscovery('appserviceSoapService', 'soap'); //第一个参数是类名(生成的wsdl文件就是以它来命名的),即Service类,第二个参数是服务的名字(这个可以随便写)。
        $r = $disco->getWSDL();
    }
}

View Code

<?php
header("Content-Type: text/html; charset=utf-8");
$client = new SoapClient('http://www.webxml.com.cn/WebServices/WeatherWebService.asmx?wsdl');

var_dump($client->__getFunctions());//把该web servcie的方法全部打印出来

$aaa = $client->getSupportDataSet();//调用其中一个无参方法

var_dump($aaa);    //输出返回值

print_r($aaa);    //输出返回值
?>

澳门新濠3559,ServiceController.php【注册、调用测试】

澳门新濠3559 9澳门新濠3559 10

<?php
/**
 * Created by PhpStorm.
 * User: 知电
 * Date: 2018-1-2
 * Time: 10:16
 */
namespace appcontrollers;
use Yii;
use yiiwebController;
class ServiceController extends Controller
{
    public $ws_url = 'http://host.com/service/ws?wsdl'; //服务注册地址
    public function init()
    {
        Yii::$app->getRequest()->enableCsrfValidation = false;
    }

    /**
     * 服务地址注册  /service/ws
     */
    public function actionWs()
    {
        //设置Yii响应格式为XML
        Yii::$app->response->format = yiiwebResponse::FORMAT_XML;
        $server = new SoapServer(dirname(dirname(__FILE__)) . '/serviceappserviceSoapService.wsdl', array('soap_version' => SOAP_1_2));
        $server->setClass('appserviceSoapService'); //注册Service类的所有方法
        $server->handle(); //处理请求
    }


    /**
     * 测试调用
     */
    public function actionTest()
    {
        $client = new SoapClient($this->ws_url, array(
            'soap_version'   => SOAP_1_2,
            'cache_wsdl' => WSDL_CACHE_NONE
        ));
        echo 'SOAP 类型';
        echo '<pre>';
        var_dump($client->__getTypes());//获取服务器上数据类型
        echo ('</pre>');
        echo 'SOAP 方法';
        echo '<pre>';
        var_dump($client->__getFunctions());//获取服务器上提供的方法
        echo ('</pre>');
        echo ("执行的结果:");
        $result = $client->__soapCall('SayHello',[111]);
        var_dump($result);
    }
}

View Code

 

备注:生成WSDL文件后,需把WSDL里面的 address location更改一下变为实际的注册地址[参考ServiceController.php说明]

 eg:

官方文档

php 调用WebService 的常见方法

写一个客户端文件如上。这个地方,我在调用.net方面的方法时,卡了很久,最后发现是对方参数格式问题,在这里特别提一下,要注意对方wsdl文件里的参数名。如果普通方式无法调通出现“php [soap:Server] 服务器无法处理请求。 --->

缺少根元素”这个提示的时候,就要注意对方wsdl文件里关于参数名的问题了。我是用了$aaa

$client->__Call("ApplyStateConfirm",array($str));这种方式调用成功的,注意这里的$str也是一个数组,键名为对方wsdl文件里规定的参数name。

这样一个web service就成功调通了。

最后,如果你在调试方法的时候,发现部分方法不起作用,那是由于php的soap的wsdl缓存造成的。在php.ini文件里关闭它,然后重启nginx。

解决方法是,修改php.ini中的soap.wsdl_cache_enabled=1(改为0),soap.wsdl_cache_ttl=86400(改为0)两项。

特别注意的是,客户端和服务端的机器都要改。

 

编辑:编程 本文来源:2 WebService 实现主要步骤,而我方使用php

关键词:

  • 上一篇:没有了
  • 下一篇:没有了