我不确定我的问题是否正确,但我想几个月前我遇到了同样的问题,所以这是我的解决方案:
首先你需要一个 HeaderHandler 类,它创建了soap header 元素,它应该是这样的:
import javax.xml.namespace.QName;
import javax.xml.soap.SOAPElement;
import javax.xml.soap.SOAPEnvelope;
import javax.xml.soap.SOAPHeader;
import javax.xml.ws.handler.MessageContext;
import javax.xml.ws.handler.soap.SOAPHandler;
import javax.xml.ws.handler.soap.SOAPMessageContext;
public class HeaderHandler implements SOAPHandler<SOAPMessageContext> {
public boolean handleMessage(SOAPMessageContext smc) {
Boolean outboundProperty = (Boolean) smc.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY);
String AUTH_TK = "http://www.myurl.com:port/subdir/etc/";
String NOPREFIX="";//no prefix
String PREFIX_XMLNS="xmlns";
String value = "123456";
if (outboundProperty.booleanValue()) {
try {
SOAPEnvelope envelope = smc.getMessage().getSOAPPart().getEnvelope();
SOAPHeader header = envelope.addHeader();
//<AuthorizationToken xmlns="http://www.myurl.com:port/subdir/etc/">
SOAPElement authorizationToken = header.addChildElement("AuthorizationToken", PREFIX_XMLNS, AUTH_TK);
//<Token>value</Token>
SOAPElement usernameToken =
authorizationToken.addChildElement("Token", NOPREFIX);
usernameToken.addTextNode(value);
//<Token>value</Token>
SOAPElement usernameToken =
authorizationToken.addChildElement("Token", PREFIX);
usernameToken.addTextNode(value);
} catch (Exception e) {
e.printStackTrace();
}
}
return outboundProperty;
}
public Set<QName> getHeaders() {
return null;
}
public void close(MessageContext arg0) {
}
public boolean handleFault(SOAPMessageContext arg0) {
return false;
}
}
之后,您创建一个 HeaderHandlerResolver 来处理标头创建并将其插入到处理程序链中:
import java.util.ArrayList;
import java.util.List;
import javax.xml.ws.handler.Handler;
import javax.xml.ws.handler.HandlerResolver;
import javax.xml.ws.handler.PortInfo;
public class HeaderHandlerResolver implements HandlerResolver {
@SuppressWarnings("unchecked")
public List<Handler> getHandlerChain(PortInfo portInfo) {
List<Handler> handlerChain = new ArrayList<Handler>();
HeaderHandler hh = new HeaderHandler();
handlerChain.add(hh);
return handlerChain;
}
}
之后,您在客户端中添加:
try{
//new service instance (your service should be extending javax.xml.ws.Service;)
YourServiceProxy service = new YourServiceProxy();
//calls the header handler resolver ;)
service.setHandlerResolver(new HeaderHandlerResolver());
//get the service
YourService port = (YourService)service.getYourService();
//call the service
port.yourMethod()
} catch (Exception e) {
e.printStackTrace();
}
顺便说一句,我没有测试这个特定的头文件,我修改了我以前的头文件处理程序,所以它可能不准确,但我认为它非常接近,我真的希望它对你有帮助,试试看并告诉我们如何它来了,如果它仍然不起作用,我会尽力帮助你。