The solution to this problem in JAX-WS is to implement the SoapMessage handler (Interface: SOAPHandler <SOAPMessageContext>). Inside this handler, you insert your HTTP header into possibly existing headers, then you transfer control to the next handler in the handler chain.
The concept of this chain of handlers is nice, you can have small classes for a specific purpose (security, logging, etc.).
In your client, you configure the chain of handlers before sending any request:
// HandlerChain installieren Binding binding = ((BindingProvider) port).getBinding(); List hchain = binding.getHandlerChain(); if (hchain == null) { hchain = new ArrayList(); } hchain.add(new HTTPUserAgentHandler()); binding.setHandlerChain(hchain);
And here is the code for HTTPUserAgentHandler:
public class HTTPUserAgentHandler implements SOAPHandler<SOAPMessageContext> { @Override public boolean handleMessage(SOAPMessageContext context) { boolean request = ((Boolean) context.get(SOAPMessageContext.MESSAGE_OUTBOUND_PROPERTY)).booleanValue(); if (request) { @SuppressWarnings("unchecked") Map<String, List<String>> headers = (Map<String, List<String>>) context .get(MessageContext.HTTP_REQUEST_HEADERS); if (null == headers) { headers = new HashMap<String, List<String>>(); } headers.put("HTTP_USER_AGENT", Collections.singletonList("user_agent")); context.put(MessageContext.HTTP_REQUEST_HEADERS, headers); } return true; } @Override public boolean handleFault(SOAPMessageContext context) { return true; } @Override public void close(MessageContext context) {} @Override public Set<QName> getHeaders() { return null; } }
dertoni
source share