hightower
hightower

Reputation: 31

Java. Soap request to web service

I need to send this request to a web service through Java:

> <soapenv:Envelope
> xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
> xmlns:gen="http://www.bossmedia.com/wsdl/genericportaladapter">   
> <soapenv:Header/>    <soapenv:Body>
>       <gen:GetPlayerDetails>
>          <request>
>             <systemUID>?</systemUID>
>             <sessionID>?</sessionID>
>          </request>
>       </gen:GetPlayerDetails>    
</soapenv:Body> </soapenv:Envelope>

What is the best way to do it, and save the response as an XML-file on my computer.

What is the best way to do it? Would be glad if you post some links which will help. I know it's popular question, but everything I have found didn't work for me.

Upvotes: 0

Views: 172

Answers (1)

lscoughlin
lscoughlin

Reputation: 2416

The JDK documentation reasonably tells you how to do this, but it does involve jumping through some hoops, so here's some sample code to get you started.

If you're going to be doing this a lot you probably want to wrap it up in some utility classes to drastically simplify this.

NOTE: I'm not sure this code is perfect, but it gives you all the correct things to google.

Best of luck!

MessageFactory messageFactory = MessageFactory.newInstance();
TransformerFactory transformerFactory = TransformerFactory.newInstance();
SOAPConnectionFactory sfc = SOAPConnectionFactory.newInstance();

Document document = null; // load your document from somewhere

// make your request message
SOAPMessage requestMessage = messageFactory.createMessage();

/// copy your message into the soap message
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(document);
DOMResult result = new DOMResult(requestMessage.getSOAPBody());
transformer.transform(source, result);

requestMessage.saveChanges();


// make the SOAP call
URL endpoint = new URL("http://example.com/endpoint");
SOAPConnection connection = sfc.createConnection();
SOAPMessage responseMessage = connection.call(requestMessage, endpoint);

// do something with the response message
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
responseMessage.writeTo(outputStream);
System.out.println(new String(outputStream.toByteArray()));

Upvotes: 1

Related Questions