如何使用Axis2将二进制文件发送到Web服务?

时间:2015-10-16 08:43:51

标签: java web-services axis2 axis

我在项目中使用了Axis 1.4,我正在转移到Axis2 1.6.3。我问这个是因为在 Axis1.4 中它很简单:

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

您只需将 DataHandler 添加到Stub,然后发送它。但是在 Axis2 中似乎不存在此方法。所以我想知道将DataHandler附加到存根的新方法是什么?

当我在互联网上搜索时,我发现您必须将DataHandler附加到MessageContextDownloading a Binary File from a Web Service using Axis2 and SOAP with Attachments)。

所以我做了正如所说:

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")));

但问题是MessageContext.getCurrentMessageContext()返回null。我认为它不起作用,因为这个代码片段应该在服务器端使用。我想要的是能够将文件发送到服务器而不是从服务器检索文件。

我可能会遗漏一些东西。也许这不是这样做的方式,无论如何任何帮助都是值得赞赏的。与此同时,我将继续在互联网上搜索,如果我发现了什么,我会告诉你:)

1 个答案:

答案 0 :(得分:0)

过了一段时间后,我想出了如何在Axis2文档中做到这一点。

转到SOAP with Attachments (SwA) with Axis2和名为发送SwA类型附件的第二部分。在这里,您将了解如何将文件发送到服务器。

这是他们提供的代码段:

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);
}

有关详细信息,请查看文档页面。

干杯!