Tuesday, May 05, 2009

Extracting SOAP attachments with Axis

It was a little hard to find this information today, so I think it would be interesting to share it here. First, what I wanted was to get the attachment for a SOAP response. The response was empty, but the attachment had a png I needed to display in my Wicket application.

It turns out that it is very simple to extract SOAP attachments. All you have to do is to write a handler that will be called during the web service call. Any number of handlers can be set in the BindingProvider. For example, this is my code to set the handlers:

MyServicePort port = mws.getMyServicePort();
BindingProvider bp = (BindingProvider) port;
Binding binding = bp.getBinding();

// Add the logging handler
List handlerList = binding.getHandlerChain();
if (handlerList == null) {
handlerList = new ArrayList();


With this code, we only need to write our handler which will handle the message and can do whatever it wants with it - including accessing attachments.

public class SOAPAttachmentHandler
implements SOAPHandler<SOAPMessageContext> {
private Collection<Attachment> attachments;

public boolean handleFault(SOAPMessageContext context) {
return true;

public boolean handleMessage(SOAPMessageContext context) {
attachments = ((SOAPMessageContextImpl)context).
return true;

public Set<QName> getHeaders() {
return null;

public void close(MessageContext context) {
// blank

public Collection<Attachment> getAttachments() {
return attachments;

The class above extracts the attachments and store then in a class variable. After invoking the web service, I can access the attachments.
Post a Comment