如何使用Apache Axis2和WSDL2Java向SOAP响应添加名称空间引用

时间:2020-03-05 18:56:39  来源:igfitidea点击:

我正在查看正在开发的Web服务的SOAP输出,并且发现了一些奇怪的东西:

<soapenv:Envelope xmlns:soapenv="http://www.w3.org/2003/05/soap-envelope">
   <soapenv:Body>
      <ns1:CreateEntityTypesResponse xmlns:ns1="http://somedomain.com/wsinterface">
         <newKeys>
            <value>1234</value>
         </newKeys>
         <newKeys>
            <value>2345</value>
         </newKeys>
         <newKeys>
            <value>3456</value>
         </newKeys>
         <newKeys xsi:nil="1" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"/>
         <newKeys xsi:nil="1" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"/>
         <errors>Error1</errors>
         <errors>Error2</errors>
      </ns1:CreateEntityTypesResponse>
   </soapenv:Body>
</soapenv:Envelope>

我有两个为nil的newKeys元素,并且两个元素都插入了xsi的命名空间引用。我想将该名称空间包含在soapenv:Envelope元素中,以便该名称空间引用仅发送一次。

我正在使用WSDL2Java生成服务框架,因此我无法直接访问Axis2 API。

解决方案

回答

使用WSDL2Java

如果我们使用了Axis2 WSDL2Java工具,那么我们会迷恋它为我们生成的内容。但是,我们可以尝试在此部分中更改框架:

// create SOAP envelope with that payload
   org.apache.axiom.soap.SOAPEnvelope env = null;
   env = toEnvelope(
       getFactory(_operationClient.getOptions().getSoapVersionURI()),
       methodName,
       optimizeContent(new javax.xml.namespace.QName
       ("http://tempuri.org/","methodName")));

//adding SOAP soap_headers
_serviceClient.addHeadersToEnvelope(env);

要将名称空间添加到信封中,请在其中的以下位置添加以下行:

OMNamespace xsi = getFactory(_operationClient.getOptions().getSoapVersionURI()).
    createOMNamespace("http://www.w3.org/2001/XMLSchema-instance", "xsi");

env.declareNamespace(xsi);

手工编码

如果我们是"手动编码"服务,则可以执行以下操作:

SOAPFactory fac = OMAbstractFactory.getSOAP11Factory();   
SOAPEnvelope envelope = fac.getDefaultEnvelope();
OMNamespace xsi = fac.createOMNamespace("http://www.w3.org/2001/XMLSchema-instance", "xsi");

envelope.declareNamespace(xsi);
OMNamespace methodNs = fac.createOMNamespace("http://somedomain.com/wsinterface", "ns1");

OMElement method = fac.createOMElement("CreateEntityTypesResponse", methodNs);

//add the newkeys and errors as OMElements here...

在AAR中公开服务

如果要在aar内部创建服务,则可能能够影响通过使用目标名称空间或者架构名称空间属性生成的SOAP消息(请参阅本文)。

希望能有所帮助。