2017-06-19 108 views
0

需要打一个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

从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集成5.0呢,你可以借用它的logi c关于此事从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); 
     } 
    } 
}