Friday, March 14, 2008

Send SOAP with Attachment use SAAJ


import java.net.MalformedURLException;
import java.net.URL;

import javax.xml.soap.AttachmentPart;
import javax.xml.soap.MessageFactory;
import javax.xml.soap.Name;
import javax.xml.soap.SOAPBody;
import javax.xml.soap.SOAPBodyElement;
import javax.xml.soap.SOAPConnection;
import javax.xml.soap.SOAPConnectionFactory;
import javax.xml.soap.SOAPElement;
import javax.xml.soap.SOAPEnvelope;
import javax.xml.soap.SOAPException;
import javax.xml.soap.SOAPFactory;
import javax.xml.soap.SOAPHeader;
import javax.xml.soap.SOAPMessage;
import javax.xml.soap.SOAPPart;


public class run {

/**
* @param args
* @throws SOAPException
* @throws MalformedURLException
* @throws UnsupportedOperationException
*/
public static void main(String[] args)
throws UnsupportedOperationException
, MalformedURLException, SOAPException {
run c = new run();
c.run();

}
public void run()
throws UnsupportedOperationException
, SOAPException
, MalformedURLException{
SOAPConnectionFactory factory =
SOAPConnectionFactory.newInstance();
SOAPConnection connection = factory.createConnection();

/// create request
SOAPMessage request = getSOAP();

java.net.URL endpoint =
new URL("http://localhost:9090/gizmo/orger");
SOAPMessage response = connection.call(request, endpoint);
}
private SOAPMessage getSOAP() throws SOAPException {
MessageFactory factory = MessageFactory.newInstance();
SOAPMessage message = factory.createMessage();
SOAPPart soapPart = message.getSOAPPart();
SOAPEnvelope envelope = soapPart.getEnvelope();
SOAPHeader header = envelope.getHeader();
SOAPBody body = envelope.getBody();

SOAPFactory soapFactory = SOAPFactory.newInstance();
Name bodyName =soapFactory.createName(
"GetLastTradePrice","m","http://wombat.ztrade.com");
SOAPBodyElement bodyElement = body.addBodyElement(bodyName);

Name name = soapFactory.createName("symbol");
SOAPElement symbol = bodyElement.addChildElement(name);
symbol.addTextNode("SUNW");

//Attachment path
AttachmentPart attachment = message.createAttachmentPart();
String stringContent = "Kajook online";
attachment.setContent(stringContent, "text/plain");
attachment.setContentId("update_address");
message.addAttachmentPart(attachment);

return message;
}

}