Access UserAgent in a Websocket session?

Using the Tyrus Java reference implementation "JSR 356 - Java API for WebSocket", I cannot find a way to access the HTTP connection that was used for Websocket updates. Thus, I cannot access the HTTP headers sent by the browser.

Is there a way to read the UserAgent HTTP header?

Bringing the Session object to TyrusSession or the like would be acceptable, I have to do this to get the remote address anyway. Sending the UserAgent again as a message inside the Websocket connection will be my backup solution.

+2
source share
1 answer

WARNING: ServerEndpointConfig is common to all endpoint instances, and multiple update requests can run simultaneously! See Comments!

The endpoint receives the configurator:

import javax.websocket.EndpointConfig; import javax.websocket.OnClose; import javax.websocket.OnMessage; import javax.websocket.OnOpen; import javax.websocket.Session; import javax.websocket.server.ServerEndpoint; @ServerEndpoint(value = "/foo", configurator = MyServerEndpointConfigurator.class) public class MyEndpoint { @OnOpen public void onOpen(Session session, EndpointConfig endpointConfig) throws Exception { String ip = ((TyrusSession) session).getRemoteAddr(); String userAgent = (String) endpointConfig.getUserProperties().get("user-agent"); ... } } 

The configurator looks like this:

 import javax.websocket.HandshakeResponse; import javax.websocket.server.HandshakeRequest; import javax.websocket.server.ServerEndpointConfig; public class MyServerEndpointConfigurator extends ServerEndpointConfig.Configurator { @Override public void modifyHandshake(ServerEndpointConfig sec, HandshakeRequest request, HandshakeResponse response) { if (request.getHeaders().containsKey("user-agent")) { sec.getUserProperties().put("user-agent", request.getHeaders().get("user-agent").get(0)); // lower-case! } } } 
0
source

Source: https://habr.com/ru/post/981648/


All Articles