使用Spring Integration创建自定义标头

时间:2017-06-19 19:22:24

标签: java soap spring-integration

需要点击其请求结构如下所示的SOAP服务

在spring integartion中,我们可以形成身体部位并点击服务并获得响应。

<?xml version="1.0"?>

<soap:Envelope
xmlns:soap="http://www.w3.org/2003/05/soap-envelope/"
soap:encodingStyle="http://www.w3.org/2003/05/soap-encoding">

<soap:Header>
 <m:Trans xmlns:m="https://www.w3schools.com/transaction/"soap:mustUnderstand="1">234
 </m:Trans>
 <authheader>
   <username> uname</username>
   <password>password</password>
 </authheader>
</soap:Header>

<soap:Body xmlns:m="http://www.example.org/stock">
  <m:GetStockPriceResponse>
  <m:Price>34.5</m:Price>
</m:GetStockPriceResponse>
</soap:Body>

但是如何与主体一起形成标题部分并将其发送到出站网关?

有人可以帮忙吗?

1 个答案:

答案 0 :(得分:1)

  

从版本5.0开始,DefaultSoapHeaderMapper支持javax.xml.transform.Source类型的用户定义标头,并将它们填充为<soapenv:Header>的子节点:

Map<String, Object> headers = new HashMap<>();

String authXml =
     "<auth xmlns='http://test.auth.org'>"
           + "<username>user</username>"
           + "<password>pass</password>"
           + "</auth>";
headers.put("auth", new StringSource(authXml));
...
DefaultSoapHeaderMapper mapper = new DefaultSoapHeaderMapper();
mapper.setRequestHeaderNames("auth");

最后我们将SOAP信封作为:

<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
    <soapenv:Header>
        <auth xmlns="http://test.auth.org">
            <username>user</username>
            <password>pass</password>
        </auth>
    </soapenv:Header>
    <soapenv:Body>
        ...
    </soapenv:Body>
</soapenv:Envelope>

如果您还不能使用Spring Integration 5.0,可以从DefaultSoapHeaderMapper借用其关于此类的自定义扩展的逻辑:

protected void populateUserDefinedHeader(String headerName, Object headerValue, SoapMessage target) {
    SoapHeader soapHeader = target.getSoapHeader();
    if (headerValue instanceof String) {
        QName qname = QNameUtils.parseQNameString(headerName);
        soapHeader.addAttribute(qname, (String) headerValue);
    }
    else if (headerValue instanceof Source) {
        Result result = soapHeader.getResult();
        try {
            this.transformerHelper.transform((Source) headerValue, result);
        }
        catch (TransformerException e) {
            throw new SoapHeaderException(
                    "Could not transform source [" + headerValue + "] to result [" + result + "]", e);
        }
    }
}