2017-06-19 65 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); 
     } 
    } 
}