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\n" ;
        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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值