在Websocket会话中访问UserAgent? [英] Access UserAgent in Websocket session?
问题描述
使用Java的JSR 356 - Java API for WebSocket的Tyrus参考实现,我找不到一种方法来访问用于Websocket升级的HTTP连接。因此,我无法访问浏览器发送的HTTP标头。
Using the Tyrus reference implementation of Java's "JSR 356 - Java API for WebSocket", I cannot find a way to access the HTTP connection that was used for the Websocket upgrades. Thus, I cannot access the HTTP headers that the browser sent.
有没有办法读取HTTP UserAgent标头?
Is there a way to read the HTTP UserAgent header?
将Session对象转换为TyrusSession或类似对象是可以接受的,我必须这样做才能获得远程地址。再次将UserAgent作为Websocket连接内的消息发送将是我的后备解决方案。
Casting a "Session" object to "TyrusSession" or similar would be acceptable, I have to do it to get the Remote Address anyway. Sending the UserAgent again as a message inside the Websocket connection would be my fallback solution.
推荐答案
警告:ServerEndpointConfig是共享的在所有端点实例中,可以同时完成多个升级请求!查看评论!
端点获取配置器:
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");
...
}
}
配置器看起来像这个:
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!
}
}
}
这篇关于在Websocket会话中访问UserAgent?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!