How to access client hostname, http headers, etc. From a Java web server server?

I followed many tutorials and sample sample code, but I have not yet seen a way to access the clientโ€™s HTTP header, hostname, etc., as we can in the servlet request object.

How can I do it?

Let's say my onOpen is defined as

@OnOpen public void onOpen(Session session) { } 

In the above method, is there a way to access the HTTP connection data using a session field? I'm fine, even if I can get into the base servlet (if any)

+6
source share
2 answers

see chapter 4.1.1.5 in the Tyrus User Guide . It takes some work to get information from ServerEnpointConfig.Configurator to the endpoint instance, but it can be done. (see ModifyRequestResponseHeadersTest.java )

+1
source

Based on link1 and link2

It finally turned out that we can get the client IP address with the following two classes, in fact you can do more with open httpservletRequest ...

ServletAwareConfigurator.java

 package examples; import java.lang.reflect.Field; import javax.servlet.http.HttpServletRequest; import javax.websocket.HandshakeResponse; import javax.websocket.server.HandshakeRequest; import javax.websocket.server.ServerEndpointConfig; import javax.websocket.server.ServerEndpointConfig.Configurator; public class ServletAwareConfigurator extends ServerEndpointConfig.Configurator { @Override public void modifyHandshake(ServerEndpointConfig config, HandshakeRequest request, HandshakeResponse response) { HttpServletRequest httpservletRequest = getField(request, HttpServletRequest.class); String sClientIP = httpservletRequest.getRemoteAddr(); config.getUserProperties().put("clientip", sClientIP); // ... } //hacking reflector to expose fields... private static < I, F > F getField(I instance, Class < F > fieldType) { try { for (Class < ? > type = instance.getClass(); type != Object.class; type = type.getSuperclass()) { for (Field field: type.getDeclaredFields()) { if (fieldType.isAssignableFrom(field.getType())) { field.setAccessible(true); return (F) field.get(instance); } } } } catch (Exception e) { // Handle? } return null; } } 

GetHttpSessionSocket.java

 package examples; import java.io.IOException; import javax.servlet.http.HttpSession; import javax.websocket.EndpointConfig; import javax.websocket.OnMessage; import javax.websocket.OnOpen; import javax.websocket.Session; import javax.websocket.server.ServerEndpoint; @ServerEndpoint(value = "/example", configurator = ServletAwareConfigurator.class) public class GetHttpSessionSocket { private Session wsSession; private String sClientIP; @OnOpen public void open(Session session, EndpointConfig config) { this.wsSession = session; this.sClientIP = (String) config.getUserProperties() .get("clientip"); } @OnMessage public void echo(String msg) throws IOException { wsSession.getBasicRemote().sendText(msg); } } 
0
source

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


All Articles