Heim > Fragen und Antworten > Hauptteil
我的java服务端为了分清各个用户使用session里的用户名做了区分,html页面使用没有问题,但是在android端访问的时候取不到cookie值。
public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler,
Map<String, Object> attributes) throws Exception {
if (request instanceof ServletServerHttpRequest) {
ServletServerHttpRequest servletRequest = (ServletServerHttpRequest) request;
// 链接webSocket时传递的参数 标识是否是特定分组, Null表明不是
//String type = (String) servletRequest.getServletRequest().getParameter("type");
HttpSession session = servletRequest.getServletRequest().getSession(false);
if (session != null) {
LoginUserInfo user = (LoginUserInfo) session.getAttribute("loginUserInfo");
// System.out.println("id");
// System.out.println(session.getId());
if (user != null) {
attributes.put("user", user);
//attributes.put("type", type);
Enumeration<String> params = servletRequest.getServletRequest().getParameterNames();
while (params.hasMoreElements()) {
String param = params.nextElement();
attributes.put(param, servletRequest.getServletRequest().getParameter(param));
}
}
}
}
return true;
}
//websocket建立
WebSocketClient websocket;
/**
* 与服务器建立websocket连接
*/
private void websocket() {
new Thread(new Runnable() {
@Override
public void run() {
//获取之前的登录信息
String Cookie = cookie.get(0).getName()+"="+cookie.get(0).getValue()+";"+ cookie.get(4).getName()+"="+cookie.get(4).getValue()+";"+ cookie.get(5).getName()+"="+cookie.get(5).getValue()+";";
application.setCookie(Cookie);
Log.i("", Cookie);
try {
HashMap<String, String> hashMap = new HashMap<String, String>();
hashMap.put("Cookie", Cookie);
// 这里的url不能带有http://
// 直接使用 xx.xx.xx.xx:端口
websocket = new WebSocketClient(new URI(HttpUrlS.WEBSOCKET), new Draft_17(), hashMap, 5000) {
@Override
public void onOpen(ServerHandshake handshakedata) {
Log.d("MyTAG", "WebSocketClient onOpen");
}
@Override
public void onMessage(final String message) {
//WebSocketUtil.handleMessage(message);
Log.i("", "有人说:" + message);
runOnUiThread(new Runnable() {
@Override
public void run() {
//Toast.makeText(MainActivity.this, "有人说:" + message, Toast.LENGTH_SHORT).show();
}
});
}
@Override
public void onClose(int code, String reason, boolean remote) {
Log.d("MyTAG", "close = " + reason);
}
@Override
public void onError(Exception ex) {
ex.printStackTrace();
Log.d("MyTAG", "onError = " + ex.toString());
}
};
websocket.connect();
} catch (URISyntaxException e) {
e.printStackTrace();
}
}
}).start();
}