如何使用JAX-WS将SOAP标头添加到SOAP请求中?

时间:2012-09-12 12:49:04

标签: soap jax-ws soapheader

我们需要使用其他团队开发的Web服务。使用JAX-WS生成Web服务。我们使用 wsimport 来生成客户端存根。

问题是我需要将以下信息作为标题与SOAP正文一起传递:

<soapenv:Header>
    <ns1:HeaderData xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd" 
                    xmlns:ns1="http://www.example.com/esb/data_type/HeaderData/v1">
        <ChannelIdentifier>ABC</ChannelIdentifier>
    </ns1:HeaderData>
</soapenv:Header>


我们正在使用:

BindingProvider.getRequestContext().put(
    BindingProvider.ENDPOINT_ADDRESS_PROPERTY,
    serviceConfig.getServiceEndPoint()
);

设置端点。

有人可以建议如何通过请求传递标题吗?

谢谢, VK

2 个答案:

答案 0 :(得分:12)

使用header = true注释

的参数@WebParam
@WebMethod
@WebResult String method(
      @WebParam String anotherParam
      @WebParam(header = true, mode = Mode.OUT) Holder<String> headerParam)  

header = true, mode = Mode.OUT表示参数headerParam仅在标题的输出中 如果您想在输入和输出中使用此参数,请创建Mode.INOUT

答案 1 :(得分:6)

我必须在标题中添加用户凭据,所以我这样做:

private void modifyRequest(String username, String password) {
    UserCredentials authHeader = new UserCredentials();
    authHeader.setUsername(username);
    authHeader.setPassword(password);
    ArrayList<Header> headers = new ArrayList<Header>(1);
    try {
        Header soapHeader = new Header(new QName(TQIntegrationV2.TQIntegrationV2Soap.getNamespaceURI(), "UserCredentials"), authHeader, new JAXBDataBinding(UserCredentials.class));
        headers.add(soapHeader);
    } catch (JAXBException ex) {
        LOGGER.error("Exception trying to serialize header: {}", ex);
    }
    ((BindingProvider) proxy).getRequestContext().put(Header.HEADER_LIST, headers);
}

一切正常。每次调用Web服务都会附带传递给此标头的用户名和密码。您可以轻松地将其更改为适用于您的情况。

修改

上面的代码使用CXF API来修改标头。我也使用JAX-WS完成了这项工作。它几乎相同,修改标题以添加用户凭据:

public class MyHandler implements SOAPHandler<SOAPMessageContext> {

    private static final Logger LOGGER = LoggerFactory.getLogger(MyHandler.class);

    private String username;

    private String password;

    /**
     * Handles SOAP message. If SOAP header does not already exist, then method will created new SOAP header. The
     * username and password is added to the header as the credentials to authenticate user. If no user credentials is
     * specified every call to web service will fail.
     *
     * @param context SOAP message context to get SOAP message from
     * @return true
     */
    @Override
    public boolean handleMessage(SOAPMessageContext context) {
        try {
            SOAPMessage message = context.getMessage();
            SOAPHeader header = message.getSOAPHeader();
            SOAPEnvelope envelope = message.getSOAPPart().getEnvelope();
            if (header == null) {
                header = envelope.addHeader();
            }
            QName qNameUserCredentials = new QName("https://your.target.namespace/", "UserCredentials");
            SOAPHeaderElement userCredentials = header.addHeaderElement(qNameUserCredentials);

            QName qNameUsername = new QName("https://your.target.namespace/", "Username");
            SOAPHeaderElement username = header.addHeaderElement(qNameUsername );
            username.addTextNode(this.username);
            QName qNamePassword = new QName("https://your.target.namespace/", "Password");
            SOAPHeaderElement password = header.addHeaderElement(qNamePassword);
            password.addTextNode(this.password);

            userCredentials.addChildElement(username);
            userCredentials.addChildElement(password);

            message.saveChanges();
            //TODO: remove this writer when the testing is finished
            StringWriter writer = new StringWriter();
            message.writeTo(new StringOutputStream(writer));
            LOGGER.debug("SOAP message: \n" + writer.toString());
        } catch (SOAPException e) {
            LOGGER.error("Error occurred while adding credentials to SOAP header.", e);
        } catch (IOException e) {
            LOGGER.error("Error occurred while writing message to output stream.", e);
        }
        return true;
    }

    //TODO: remove this class after testing is finished
    private static class StringOutputStream extends OutputStream {

        private StringWriter writer;

        public StringOutputStream(StringWriter writer) {
            this.writer = writer;
        }

        @Override
        public void write(int b) throws IOException {
            writer.write(b);
        }
    }

    @Override
    public boolean handleFault(SOAPMessageContext context) {
        LOGGER.debug("handleFault has been invoked.");
        return true;
    }

    @Override
    public void close(MessageContext context) {
        LOGGER.debug("close has been invoked.");
    }

    @Override
    public Set<QName> getHeaders() {
        LOGGER.debug("getHeaders has been invoked.");
        return null;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}

我在Spring配置中定义了这个处理程序,如下所示:

<bean id="soapHandler" class="your.package.MyHandler">
    <property name="username" value="testUser"/>
    <property name="password" value="testPassword"/>
</bean>

<jaxws:client "...">
    <jaxws:handlers>
        <ref bean="soapHandler"/>
    </jaxws:handlers>
</jaxws:client>

您需要做的就是实现SOAPHandler<SOAPMessageContext>界面,覆盖其方法,然后您可以使用SOAP消息执行任何操作。