JAX-WS client: maintain session/cookies across multiple services
Asked Answered
C

2

11

I'm using Netbeans to automatically create webservice clients based off WSDL files. This works well, except the webservices I'm using require that I pass in a custom cookie in the HTTP header to every webservice in order to prove my identity.

I use one webservice named Utility to get my authorization. This sets a cookie which needs to be provided in all subsequent calls to any webservice.

This can be accomplished by setting javax.xml.ws.session.maintain to true on the BindingProvider of the port for the webservice. This works great for subsequent calls to the methods in the Utility webservice. The problem is that this only maintains the session/cookie for that single webservice. I need it across others as well.

I need the cookie passed in to a separate webservice named History How can I accomplish this? Is it feasible to have a super Service class which both Utility and History could extend and share the same session state with?

Caracas answered 5/2, 2013 at 2:19 Comment(0)
C
17

I've found a solution.

You can get response headers using this after you've made the call:

((BindingProvider)port).getResponseContext().get(MessageContext.HTTP_RESPONSE_HEADERS);

Find the Set-Cookie header and store its value.

Then before your next request (in any webservice) you can set the Cookie header:

((BindingProvider)port).getRequestContext().put(
            MessageContext.HTTP_REQUEST_HEADERS,
                Collections.singletonMap("Cookie", Collections.singletonList(cookieValue)
            )
        );
Caracas answered 5/2, 2013 at 14:47 Comment(1)
Perhaps you have to add that extracting the Cookie this way is only possible directly after the first call - since only there "Set-Cookie" is set. But nontheless... thank you very much. This saved me a lot of time.Fussbudget
P
4

Just commenting because solution above didn't work for me. I got UnsupportedOperationException. I believe issue was caused because singletonMap doesn't allow changes. xml headers were also needed, so I set those first.

Map<String, List<String>> headers= CastUtils.cast((Map)port.getRequestContext().get("javax.xml.ws.http.request.headers"));
if (headers == null) {
    headers = new HashMap<String, List<String>>();
    port.getRequestContext().put("javax.xml.ws.http.request.headers", headers);
}

headers.put("Cookie", Collections.singletonList(cookieValue));
((BindingProvider)port).getRequestContext().put(MessageContext.HTTP_REQUEST_HEADERS, headers); 
Phalansterian answered 11/6, 2014 at 19:23 Comment(3)
Yes, SingletonMaps are immutable -- i used it merely as a convenienceCaracas
You should review code to get it more compact, knowing MessageContext.HTTP_REQUEST_HEADERS == "javax.xml.ws.http.request.headers"Belga
His version is actually one char shorter even including quotes, but I know what you mean. Using a constant is certainly safer. :)Zillion

© 2022 - 2024 — McMap. All rights reserved.