本示例演示如何利用PHP调用由Java语言编写的Web Service接口。在通信过程中,客户端负责提交两个String类型的参数,而服务端则返回一个对象类型的数据结构。在服务端实现上,采用AXIS-1.4作为底层的SOAP引擎;客户端环境为PHP 5.2.9版本,并选用NuSOAP库来处理SOAP消息的封装与解析。
服务端逻辑部分
首先定义用于数据传输的对象类,需实现序列化接口以确保对象在网络传输中的完整性。代码如下: import java.io.Serializable;
具体实现如下: public class Person implements Serializable { /** * */ private static final long serialVersionUID = -410186774891162281L; private String username; private int age; private boolean sex;// true:male;false:female
提供获取用户名的方法: public String getUsername() { return username; }
提供设置用户名的方法: public void setUsername(String username) { this.username = username; }
提供获取年龄的方法: public int getAge() { return age; }
提供设置年龄的方法: public void setAge(int age) { this.age = age; }
提供获取性别状态的方法: public boolean getSex() { return sex; }
提供设置性别状态的方法: public void setSex(boolean sex) { this.sex = sex; } } 接下来是服务类的定义: 复制代码 代码如下: public class UserLogin {
服务类中实现登录验证逻辑,根据传入的用户名和密码匹配预设值,并填充Person对象返回。若验证失败则返回null。代码如下: public Person login(String loginName, String loginPasswd) { Person aPerson = new Person(); if (loginName.equals("laoli") && loginPasswd.equals("111111")) { aPerson.setUsername("老李"); aPerson.setAge(55); aPerson.setSex(true); } else if (loginName.equals("xiaoli") && loginPasswd.equals("123456")) { aPerson.setUsername("小丽"); aPerson.setAge(23); aPerson.setSex(false); } else { aPerson = null; } return aPerson; }
} 客户端实现部分 复制代码 代码如下:
/* * Created on 2011-10-12 * Author wanghao * * package_name/userLoginClient.php */ header("Content-Type: text/html;charset=utf-8"); // Pull in the NuSOAP code require_once ("libs/nusoap.php"); // Create the client instance $client = new nusoapclient('http://localhost:8080/axis/services/UserLoginWS?wsdl', true); $client->soap_defencoding = 'utf-8'; $client->decode_utf8 = false; $client->xml_encoding = 'utf-8'; // Check for an error $err = $client->getError(); if ($err) { // Display the error echo '
Constructor error
' . $err . '';
// At this point, you know the call that follows will fail
}
// Call the SOAP method
$param=array('loginName'=>'laoli', 'loginPasswd'=>'111111');
$result = $client->call('login', $param);
// Check for a fault
if ($client->fault) {
echo 'Fault
';
print_r($result);
echo '';
} else {
// Check for errors
$err = $client->getError();
if ($err) {
// Display the error
echo 'Error
' . $err . '';
} else {
// Display the result
echo 'Result
';
print_r($result);
echo '';
}
}
echo '
';
$param=array('loginName'=>'xiaoli', 'loginPasswd'=>'123456');
$result = $client->call('login', $param);
// Check for a fault
if ($client->fault) {
echo 'Fault
';
print_r($result);
echo '';
} else {
// Check for errors
$err = $client->getError();
if ($err) {
// Display the error
echo 'Error
' . $err . '';
} else {
// Display the result
echo 'Result
';
print_r($result);
echo '';
}
}
?>