zoukankan      html  css  js  c++  java
  • [PHP]php发布和调用Webservice接口的案例

    分两步走:1.服务端发布接口;2.客户端调用方法

    1.服务端发布接口:

    需要nusoap工具,下载地址:http://sourceforge.net/projects/nusoap/

    下载完和要发布接口的php文件放在同一目录下。

    服务端发布接口soapserver.php例子:

    <?php
    require_once('./lib/nusoap.php');
    $soap = new soap_server;

    $soap->soap_defencoding = 'UTF-8';
    $soap->decode_utf8 = false;
    $soap->xml_encoding = 'UTF-8';
    $soap->configureWSDL('reverse','add2numbers');
    //$server->configureWSDL('add2numbers');

    $soap->register('reverse',
    array('str' => 'xsd:string'),
    array('return' => 'xsd:string')
    );
    $soap->register('add2numbers',
    array('num1' => 'xsd:int','num2' => 'xsd:int'),
    array('return' => 'xsd:int')
    );

    //Check variable set?
    $HTTP_RAW_POST_DATA = isset($HTTP_RAW_POST_DATA)? $HTTP_RAW_POST_DATA:'';

    //service handle the client data
    $soap->service($HTTP_RAW_POST_DATA);
    //echo $server;
    /*
    * RPC function
    * @param $name
    */
    function reverse($str){
    $retval = "";
    if(strlen($str) < 1) {
    return new soap_fault('Client','','Invalid string');
    }
    for ($i = 1; $i <= strlen($str); $i++) {
    $retval .= $str[(strlen($str) - $i)];
    }
    return $retval;
    }

    function add2numbers($num1, $num2) {
    if (trim($num1) != intval($num1)) {
    return new soap_fault('Client', '', 'The first number is invalid');
    }
    if (trim($num2) != intval($num2)) {
    return new soap_fault('Client', '', 'The second number is invalid');
    }
    return ($num1 + $num2);
    }
    ?>

    发布的结果截图:

     

     wsdl的说明截图:

    2.客户端调用接口:

    调用接口soapclient.php例子:

    <?php
    require_once "./lib/nusoap.php";

    $client = new nusoap_client("http://192.168.119.21/soapserver.php");
    $client->soap_defencoding = 'UTF-8';
    $client->decode_utf8 = false;
    $client->xml_encoding = 'UTF-8';

    $str = "This string will be reversed";
    $params1 = array('str'=>$str);
    $reversed = $client->call('reverse',$params1);
    echo "If you reverse '$str', you get '$reversed'<br> ";

    $n1 = 5;
    $n2 = 14;
    $params2 = array('num1'=>$n1, 'num2'=>$n2);
    $added = $client->call('add2numbers', $params2);
    echo "If you add $n1 and $n2 you get $added<br> ";
    ?>

    调用后结果:

  • 相关阅读:
    第08组 Alpha事后诸葛亮
    第08组 Alpha冲刺(4/4)
    第08组 Alpha冲刺 (3/4)
    第08组 Alpha冲刺 (2/4)
    第08组 Alpha冲刺(1/4)
    第08组 团队git现场编程实战
    第二次结对编程作业
    团队项目-需求分析报告
    团队项目—选题报告
    2019 SDN上机第7次作业
  • 原文地址:https://www.cnblogs.com/liangxuehui/p/4606935.html
Copyright © 2011-2022 走看看