Java Reference
In-Depth Information
Creating a Ruby Client for a Web Service
Problem
You want to create a Ruby program that consumes a web service written in Java.
Solution
Use the
wsdl2ruby
program or, preferably, the
SOAP::WSDLDriverFactory
class.
Discussion
The
wsdl2ruby
program is similar to
wsdl.exe
in .NET or
wsdl2java
in Apache Axis, or
wsimport
. The
WSDLDriverFactory
class dynamically generates code for you at runtime
based on a WSDL, which hides the complexity of dealing with services.
Let's make a client that invokes a Java web service calculator. Here's the most relevant part
from the schema for this example:
<xs:complexType name="add">
<xs:sequence>
<xs:element name="i" type="xs:int"/>
<xs:element name="j" type="xs:int"/>
</xs:sequence>
</xs:complexType>
This WSDL defines an
add
operation, with two parameters,
i
and
j
, which are integers to be
added. It's a document/literal wrapped service. Now you can make a Ruby program that will
invoke this service, which I've written in Java (see
Example 12-13
)
.
Example12-13.JavaWsdlDriverClient.rb
require 'soap/wsdlDriver'
wsdl = 'http://localhost:8080/CalculatorApp/CalculatorWSService?wsdl'
service = SOAP::WSDLDriverFactory.new(wsdl).create_rpc_driver
service.wiredump_dev = STDOUT
result = service.add(:i=>'6', :j=>'9')
puts "Result is %s!" % "#{result.return}"
Here the
require
statement indicates the library that you want to use. You create a variable
called
wsdl
, and because Ruby is not strongly typed like Java is, you don't need to give the
variable a reference type; Ruby can determine it from context. Then create a proxy instance