20

オブジェクトをのsoapヘッダーに追加するにはどうすればよいですか?org.springframework.ws.WebServiceMessage

これは私が最終的に見ている構造です:

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

6 に答える 6

39

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を修正する必要があります。

于 2010-02-16T19:10:39.440 に答える
11

あなたは以下のようにすることができます:

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());
于 2016-06-16T11:04:54.393 に答える
4

WebServiceMessagetoをキャストする必要がありますSoapMessage。これにはgetSoapHeader()、ヘッダーを変更するために使用できるメソッドがあります。次に、SoapHeader要素を追加するためのさまざまなメソッドがあります。getResult()これには、(操作の出力として使用できますTransformer.transform())が含まれます。

于 2010-02-16T17:24:22.107 に答える
3
I tried many options and finally below one worked for me if you have to send soap header with authentication(Provided authentication object created by wsimport) and also need to set soapaction.

public Response callWebService(String url, Object request)

{
    Response res = null;
    log.info("The request object is " + request.toString());

    try {
        
        

        res = (Response) getWebServiceTemplate().marshalSendAndReceive(url, request,new WebServiceMessageCallback() {
                 @Override
                  public void doWithMessage(WebServiceMessage message) {
                    try {
                      // get the header from the SOAP message
                      SoapHeader soapHeader = ((SoapMessage) message).getSoapHeader();

                      // create the header element
                      ObjectFactory factory = new ObjectFactory();
                      Authentication auth =
                          factory.createAuthentication();
                      auth.setUser("****");
                      auth.setPassword("******");
                     ((SoapMessage) message).setSoapAction(
                                "soapAction");

                      JAXBElement<Authentication> headers =
                          factory.createAuthentication(auth);

                      // create a marshaller
                      JAXBContext context = JAXBContext.newInstance(Authentication.class);
                      Marshaller marshaller = context.createMarshaller();

                      // marshal the headers into the specified result
                      marshaller.marshal(headers, soapHeader.getResult());
                      
                    } catch (Exception e) {
                      log.error("error during marshalling of the SOAP headers", e);
                    }
                  }
                });

        
    } catch (Exception e) {
        e.printStackTrace();
    }
    return res;

}
  
于 2020-07-10T19:09:09.383 に答える
0

Response response = (Response)getWebServiceTemplate() .marshalSendAndReceive(request, new HeaderModifier());

クラスHeaderModifierを作成し、doWithMessageをオーバーライドします

public class HeaderModifier implements WebServiceMessageCallback {

     private static PrintStream out = System.out;
     
    @Override
    public void doWithMessage(WebServiceMessage message) throws IOException {
          SaajSoapMessage soapMessage = (SaajSoapMessage) message;

                SoapEnvelope soapEnvelope = soapMessage.getEnvelope();
                SoapHeader soapHeader = soapEnvelope.getHeader();
                
                //Initialize QName for Action and To 
                QName action = new QName("{uri}","Action","{actionname}");
                QName to = new QName("{uri}","To","{actionname}");
                
                
                soapHeader.addNamespaceDeclaration("{actionname}", "{uri}");
                
            
                SoapHeaderElement soapHeaderElementAction = soapHeader.addHeaderElement(action);
                SoapHeaderElement soapHeaderElementTo =  soapHeader.addHeaderElement(to);
                
                
            
                soapHeaderElementAction.setText("{text inside the tags}");
                
            
                soapHeaderElementTo.setText("{text inside the tags}");
                
            
                soapMessage.setSoapAction("{add soap action uri}");
                
            
                soapMessage.writeTo(out);
        
    }
}
于 2019-06-28T20:39:22.710 に答える
0

これは、子要素のKey-Valueマップを作成することでも実現できます。

final Map<String, String> elements = new HashMap<>();
elements.put("username", "username");
elements.put("password", "password");

子要素の名前空間とプレフィックスをsoapヘッダー内に設定します。

final String LOCAL_NAME = "credentials";
final String PREFIX = "";
final String NAMESPACE = "http://example.com/auth";

次に、WebServiceTemplateのメソッドを呼び出して、 WebServiceMessageCallbackのメソッドdoWithMessageを次のようmarshalSendAndReceiveにオーバーライドできます。

Object response = getWebServiceTemplate().marshalSendAndReceive(request, (message) -> {
    if (message instanceof SaajSoapMessage) {
        SaajSoapMessage saajSoapMessage = (SaajSoapMessage) message;
        SOAPMessage soapMessage = saajSoapMessage.getSaajMessage();
        SOAPPart soapPart = soapMessage.getSOAPPart();

        if (Objects.nonNull(elements)) {
            try {
                SOAPEnvelope soapEnvelope = soapPart.getEnvelope();
                SOAPHeader soapHeader = soapEnvelope.getHeader();
                Name headerElementName = soapEnvelope.createName(
                        LOCAL_NAME,
                        PREFIX,
                        NAMESPACE
                );
                SOAPHeaderElement soapHeaderElement = soapHeader.addHeaderElement(headerElementName);

                elements.forEach((key, value) -> {
                    try {
                        SOAPElement element = soapHeaderElement.addChildElement(key, PREFIX);
                        element.addTextNode(value);
                    } catch (SOAPException e) {
                        // error handling
                    }
                });

                soapMessage.saveChanges();
            } catch (SOAPException e) {
                // error handling
            }
        }
    }
});

上記の手順により、次のようになります。

<env:Envelope xmlns:env="http://www.w3.org/2003/05/soap-envelope">
   <env:Header>
      <credentials xmlns="http://example.com/auth">
         <password>password</password>
         <username>username</username>
      </credentials>
   </env:Header>
   <env:Body>
      <!--  your payload -->
   </env:Body>
</env:Envelope>
于 2020-07-27T13:12:50.713 に答える