使用JAX-WS的典型SOAP客户端请求可能是
FooService service = new FooService();
FooPort port = service.getFooPort();
FooPayload payload = new FooPayload();
payload.setHatSize(3);
payload.setAlias("The Hat");
...
port.processRequest(payload);
这会生成类似
的HTTP请求内容<?xml ... ?>
<S:Envelope xmlns:S="http://...soap-envelope">
<S:Body>
<!-- payload -->
</S:Body>
</S:Envelope>
通过操作port.processRequest()调用的参数,您只能影响“payload”部分。您不能影响XML消息的外部部分。
我想在SOAP Body
之前插入一个SOAP标头<S:Header>
<X:Security xmlns:X="http://...wsssecurity...>
<X:BinarySecurityToken>kjh...897=</X:BinarySecurityToken>
</X:Security>
</S:Header>
我该怎么做?
答案 0 :(得分:18)
感谢Nuno,
我一看到如何正确登录stackoverflow.com,我就会回答您的问题。
与此同时,我最终得到的代码是:
FooService service = new FooService();
service.setHandlerResolver(new HandlerResolver() {
public List<Handler> getHandlerChain(PortInfo portInfo) {
List<Handler> handlerList = new ArrayList<Handler>();
handlerList.add(new RGBSOAPHandler());
return handlerList;
}
});
FooPort port = service.getFooPort();
FooPayload payload = new FooPayload();
payload.setHatSize(3);
payload.setAlias("The Hat");
...
port.processRequest(payload);
和
class RGBSOAPHandler implements SOAPHandler<SOAPMessageContext> {
public Set<QName> 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) {
//
}
}
答案 1 :(得分:1)
你可能想看一下处理程序和处理程序链.-我最近不得不在给定的Webservice调用中添加一个cookie,这就是我做的方式,只是创建了一个拦截初始调用并注入cookie的处理程序,你也可以使用Pivot Handler操作调用头
答案 2 :(得分:0)
用于添加Soap标头,如果您在Web应用程序服务器上实现WS,则在根据WS-SECURITY标准进行配置后,Was将在标头处添加安全性部分,例如web-policy等。我不这样做理解为什么需要添加自己,除了加密的内容部分,如加密密码等