将 SoapHeader 添加到 org.springframework.ws.WebServiceMessage

2022-09-02 05:16:24

如何将对象添加到 soap 标头中org.springframework.ws.WebServiceMessage

这就是我希望最终得到的结构:

 <soap:Header>
    <credentials xmlns="http://example.com/auth">
      <username>username</username>
      <password>password</password>
    </credentials>
  </soap:Header>

答案 1

基本上,您需要在客户端中使用 WebServiceMessageCallback 在消息创建后但在发送之前对其进行修改。@skaffman已经非常准确地描述了代码的其余部分,因此整个内容可能如下所示:

public void marshalWithSoapActionHeader(MyObject o) {

    webServiceTemplate.marshalSendAndReceive(o, new WebServiceMessageCallback() {

        public void doWithMessage(WebServiceMessage message) {
            try {
                SoapMessage soapMessage = (SoapMessage)message;
                SoapHeader header = soapMessage.getSoapHeader();
                StringSource headerSource = new StringSource("<credentials xmlns=\"http://example.com/auth\">\n +
                        <username>"+username+"</username>\n +
                        <password>"+password"+</password>\n +
                        </credentials>");
                Transformer transformer = TransformerFactory.newInstance().newTransformer();
                transformer.transform(headerSource, header.getResult());
            } catch (Exception e) {
                // exception handling
            }
        }
    });
}

就个人而言,我发现Spring-WS对于这样的基本需求来说很难,他们应该修复SWS-479


答案 2

您可以执行以下操作:

public class SoapRequestHeaderModifier implements WebServiceMessageCallback {
 private final String userName = "user";
 private final String passWd = "passwd";

 @Override
 public void doWithMessage(WebServiceMessage message) throws IOException, TransformerException {
  if (message instanceof SaajSoapMessage) {
   SaajSoapMessage soapMessage = (SaajSoapMessage) message;
   MimeHeaders mimeHeader = soapMessage.getSaajMessage().getMimeHeaders();
   mimeHeader.setHeader("Authorization", getB64Auth(userName, passWd));
  }
 }

 private String getB64Auth(String login, String pass) {
  String source = login + ":" + pass;
  String retunVal = "Basic " + Base64.getUrlEncoder().encodeToString(source.getBytes());
  return retunVal;
 }
}

然后

Object response = getWebServiceTemplate().marshalSendAndReceive(request, new SoapRequestHeaderModifier());

推荐