JAVA调用PHP SOAP服务的示例
Image you had a php service that would connect to a mysql database and return query results via soap.
That php service (SOAP server) could look like that:
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 |
if
(!isset($_SERVER["PHP_AUTH_USER"])) {
Header("WWW-Authenticate: Basic realm="nedeco soap_service"");
Header("HTTP/1.0 401 Unauthorized");
echo
"Sorry no login, no service
";
exit;
} else
if ($_SERVER["PHP_AUTH_USER"]=="service"
&& $_SERVER["PHP_AUTH_PW"] ==
"ilovenedeco") {
class
db_connector {
var
$host = "localhost";
var
$user = "root";
var
$pass = "";
var
$dbname = "mysql";
var
$db_link = false;
function
db_connector()
{
$this->db_connect($this->host,$this->user,$this->pass,$this->dbname);
$this->db_link->set_charset("utf8");
}
function
db_connect($host,$user,$pass,$dbname)
{
if
(!$this->db_link =
new mysqli($host,$user,$pass,$dbname))
return
new SoapFault("db_error",
"no database link",
"db_connector",
"");
if
(!$this->db_choose($dbname))
new
SoapFault("db_error",
"non existing database",
"db_connector",
"");
}
function
db_choose($dbname)
{
return
$this->db_link->select_db($dbname);
}
function
db_query($query)
{
if
(!$this->db_link) {
return
new SoapFault("db_error",
"no database connection available",
"db_connector",
"");
}
if
($this->db_link->real_query($query))
{
if
($result
= $this->db_link->store_result()) {
$i
= 0;
while($row=$result->fetch_object())
{
$val[$i] =
$row;
$i++;
}
if
($i==1)
return
$val[0];
else
return
$val;
}
elseif (preg_match("/insert/i",
$query) > 0) {
return
$this->db_link->insert_id;
}
else
return
null;
}
return
new SoapFault("db_error",
"the query is faulty",
"db_connector",
"");
}
public
function __destruct() {
$this->db_link->close();
}
}
class
MySoapClass {
var
$class_db;
public
function __construct() {
$this->class_db =
new db_connector;
}
public
function __destruct() {
unset($this->class_db);
}
public
function echo_test($test) {
return
"you wrote: ".$test;
}
public
function get_names($name) {
return
$this->class_db->db_query("select * from userdb.usertable where `name`="".$name."";");
}
}
$server
= new
SoapServer(null, array("uri"
=> "http://development.nedeco.de/simple_soap_server.php"));
$server->setClass("MySoapClass");
$server->handle();
}
|
To make this example work you would need to create a database called userdb with an usertable. This would be the sql to create the table and put in some data:
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
CREATE
TABLE `userdb`.`usertable` (
`id` INT
NOT NULL
AUTO_INCREMENT PRIMARY
KEY ,
`name`
VARCHAR( 256 )
NOT NULL
,
`email` VARCHAR( 256 )
NOT NULL
) ENGINE = MYISAM
INSERT
INTO `userdb`.`usertable` (
`id` ,
`name` ,
`email`
)
VALUES
(
NULL
, "alexander",
"a.balsam@nedeco.de"
), (
NULL
, "alexander",
"alexander@balsam.de"
);
|
After everything is created you would like to call the function get_names via a java program:
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 |
public
class soapclient {
public
static void
main(String [] args) {
String operation =
"get_names";
String urn =
"framework";
String destination =
"http://development.nedeco.de/simple_soap_server.php";
try
{
// First create the connection
SOAPConnectionFactory soapConnFactory = SOAPConnectionFactory.newInstance();
SOAPConnection connection = soapConnFactory.createConnection();
// Next, create the actual message
MessageFactory messageFactory = MessageFactory.newInstance();
SOAPMessage message = messageFactory.createMessage();
SOAPPart soapPart = message.getSOAPPart();
SOAPEnvelope envelope = soapPart.getEnvelope();
// set username and password into header for basic authentication
String authorization = Base64Coder.encodeString("service:ilovenedeco");
MimeHeaders hd = message.getMimeHeaders();
hd.addHeader("Authorization",
"Basic " + authorization);
// Create and populate the body
SOAPBody body = envelope.getBody();
// Create the main element and namespace
SOAPElement bodyElement = body.addChildElement(envelope.createName(operation,
"ns1", "urn:"+urn));
bodyElement.addChildElement("in0").addTextNode("alexander");
// Save the message
message.saveChanges();
// Send the message and get the reply
SOAPMessage reply = connection.call(message, destination);
// Retrieve the result - no error checking is done: BAD!
soapPart = reply.getSOAPPart();
envelope = soapPart.getEnvelope();
body = envelope.getBody();
Node returnvalue = (Node) body.getChildElements().next();
if
(returnvalue != null) {
if
(returnvalue.getChildNodes().item(0).getNodeName().equals("return")) {
List<HashMap<String,String>> ReturnArray =
new ArrayList<HashMap<String,String>>();
// we have some values, trying to read them now
for
(int
i=0;i<returnvalue.getChildNodes().item(0).getChildNodes().getLength();i++) {
if
(returnvalue.getChildNodes().item(0).getChildNodes().item(i).getNodeName().equals("item")) {
HashMap<String,String> keyvaluepairs =
new HashMap<String,String> ();
for
(int
j=0;j<returnvalue.getChildNodes().item(0).getChildNodes().item(i).getChildNodes().getLength();j++){
System.out.print("("+returnvalue.getChildNodes().item(0).getChildNodes().item(i).getChildNodes().getLength()+"/"+j+")");
String key=returnvalue.getChildNodes().item(0).getChildNodes().item(i).getChildNodes().item(j).getNodeName();
String value;
if
(returnvalue.getChildNodes().item(0).getChildNodes().item(i).getChildNodes().item(j).getChildNodes().getLength() ==
1) {
value=returnvalue.getChildNodes().item(0).getChildNodes().item(i).getChildNodes().item(j).getChildNodes().item(0).getNodeValue();
}
else {
value ="";
}
keyvaluepairs.put ( key, value );
System.out.println("added "+key+" =
"+value);
}
ReturnArray.add(keyvaluepairs);
}
else {
System.out.println("No items ");
}
}
}
else {
System.out.println("no return"
+ returnvalue.getChildNodes().item(0).getNodeName());
}
}
else {
System.out.println("nothing returned");
}
// Close the connection
connection.close();
}
catch (Exception e) {
System.out.println(e.getMessage());
}
}
}
|
This java code makes a soap call to the php soap server and puts the returned database result into a List of Hashmaps with the database entries. The example output of the java program looks like that:
(3/0)added id = 1
(3/1)added name = alexander
(3/2)added email = a.balsam@nedeco.de
(3/0)added id = 2
(3/1)added name = alexander
(3/2)added email = alexander@balsam.de
If you have any input on this leave a comment or write some additional code and send it to me.
- 上一篇: JAVA调用PHP SOAP服务
- 下一篇: java调用php的webservice示例
