Search code examples
javaweb-servicesapache-axisaxis

How do you send a binary file to a webservice using Axis2?


I was using Axis 1.4 on a project and I am moving to Axis2 1.6.3. I am asking this because in Axis1.4 it was quite straightforward :

myStub.addAttachment(new DataHandler(new FileDataSource("path_to_file")));

You just add a DataHandler to the Stub and then send it. But in Axis2 it seems that this method doesn't exist. So I was wondering what is the new way of attaching a DataHandler to a stub ?

As I was searching on the internet, I find out that you have to attach the DataHandler to the MessageContext (Downloading a Binary File from a Web Service using Axis2 and SOAP with Attachments).

So I did As it is said :

MessageContext messageContext = MessageContext.getCurrentMessageContext();
OperationContext operationContext = messageContext.getOperationContext(); 
MessageContext outMessageContext = operationContext.getMessageContext(WSDLConstants.MESSAGE_LABEL_OUT_VALUE);
outMessageContext.addAttachment(new DataHandler(new FileDataSource("path_to_file")));

But the problem is that MessageContext.getCurrentMessageContext() return null. I think that it is not working because this snippet should be used on the server side. What I want is to be able to send a file to the server not retrieve one from the server.

I might be missing something. Maybe this is not the way to do it, anyway any help is appreciated. In the meantime I'll keep up searching on the internet and if I find something I'll let you know :)


Solution

  • So after some time I figured out how to do it on Axis2 Documentation.

    Go to SOAP with Attachments (SwA) with Axis2 and on the second section named Sending SwA Type Attachments. Here you will find out how to send a file to the server.

    This is the code snippet they provide :

    public void uploadFileUsingSwA(String fileName) throws Exception {
    
        Options options = new Options();
        options.setTo(targetEPR);
        options.setProperty(Constants.Configuration.ENABLE_SWA, Constants.VALUE_TRUE);
        options.setTransportInProtocol(Constants.TRANSPORT_HTTP);
        options.setSoapVersionURI(SOAP11Constants.SOAP_ENVELOPE_NAMESPACE_URI);
        options.setTo(targetEPR);
    
        ServiceClient sender = new ServiceClient(null,null);
        sender.setOptions(options);
        OperationClient mepClient = sender.createClient(ServiceClient.ANON_OUT_IN_OP);
    
        MessageContext mc = new MessageContext();   
        mc.setEnvelope(createEnvelope());
        FileDataSource fileDataSource = new FileDataSource("test-resources/mtom/test.jpg");
        DataHandler dataHandler = new DataHandler(fileDataSource);
        mc.addAttachment("FirstAttachment",dataHandler);
    
        mepClient.addMessageContext(mc);
        mepClient.execute(true);
    }
    

    For more information go check the page of the documentation.

    Cheers !