How do I add a SOAP Header using Java JAX-WS

后端 未结 3 472
逝去的感伤
逝去的感伤 2020-12-04 20:02

A typical SOAP client request using JAX-WS might be

FooService service = new FooService();
FooPort port = service.getFooPort();
FooPayload payload = new FooP         


        
3条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-04 20:49

    Thanks Nuno,

    Just as soon as I work out how to log in properly to stackoverflow.com I'll do the right thing with your reply.

    In the mean time here's the code I ended up with:

    FooService service = new FooService();
    service.setHandlerResolver(new HandlerResolver() {
        public List getHandlerChain(PortInfo portInfo) {
            List handlerList = new ArrayList();
            handlerList.add(new RGBSOAPHandler());
            return handlerList;
        }
    });
    FooPort port = service.getFooPort();
    FooPayload payload = new FooPayload();
    payload.setHatSize(3);
    payload.setAlias("The Hat");
    ...
    port.processRequest(payload);
    

    and

    class RGBSOAPHandler implements SOAPHandler {
    
        public Set getHeaders() {
            return new TreeSet();
        }
    
        public boolean handleMessage(SOAPMessageContext context) {
            Boolean outboundProperty = 
                (Boolean) context.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY);
            if (outboundProperty.booleanValue()) {
                SOAPMessage message = context.getMessage();
                try {
                    SOAPEnvelope envelope = context.getMessage()
                            .getSOAPPart().getEnvelope();
                    SOAPFactory factory = SOAPFactory.newInstance();
                    String prefix = "X";
                    String uri = "http://...wsssecurity...";
                    SOAPElement securityElem = 
                            factory.createElement("Security",prefix,uri);
                    SOAPElement tokenElem = 
                            factory.createElement("BinarySecurityToken",prefix,uri);
                    tokenElem.addTextNode("kjh...897=");
                    securityElem.addChildElement(tokenElem);
                    SOAPHeader header = envelope.addHeader();
                    header.addChildElement(securityElem);
    
                } catch (Exception e) {
                    System.out.println("Exception in handler: " + e);
                }
            } else {
                // inbound
            }
            return true;
        }
    
        public boolean handleFault(SOAPMessageContext context) {
            throw new UnsupportedOperationException("Not supported yet.");
        }
    
        public void close(MessageContext context) {
            //
        }
    }
    

提交回复
热议问题