Friday, April 15, 2011

Simple SOAP client

I needed a quick and simple SOAP client to verify some odd return values from a web service. I also wanted the client to be able to send and receive badly formatted XML for testing purposes, and preferably pretty print the xml. Didn't feel very appealing to try to do this in Java, so I decided to do it with JRuby.

Ruby already has the soap4r library, which given a wsdl url gives you convenient objects for performing requests. Unfortunately soap4r tries to retrieve the wsdl with a http GET, and the service is configured to only respond to POST (yes, even for wsdl request). So I decided to go directly to the HTTPClient. Here it is, including pretty printing the output, if someone else finds it useful.

require 'rubygems'
require 'httpclient'

soapbody = <<-eos
<soap:Envelope>
** your soapy stuff goes here **
</soap:Envelope>
eos

header = {'Content-Type' => 'application/soap+xml'}
endpoint = "http://localhost:8080/testService"

client = HTTPClient.new
#Uncomment next line if you want to see requests and responses as sent.
#client.debug_dev=STDOUT
result = client.post(endpoint, soapbody, header)

puts '== Content'
print result.body

There are some more sample usages of HTTPClient here, the class documentation is here.

If you have a valid xml reply and want to pretty print it, add:

require "jrexml"
require "rexml/document"
doc = REXML::Document.new result.body
doc.write( STDOUT, 3 )

No comments: