socket.io Android库身份验证

时间:2015-10-14 13:50:53

标签: android node.js socket.io sails.js socket.io-java-client

我使用这个库(https://github.com/socketio/socket.io-client-java)将我的Android应用程序与我的Sails socket.io连接。

以下是我使用的代码:

final Socket socket = IO.socket(Constants.LOCAL_URL+"?__sails_io_sdk_version=0.11.0");
socket.on(Socket.EVENT_CONNECT, new Emitter.Listener()
            {

                @Override
                public void call(Object... args)
                {
                    JSONObject obj1 = new JSONObject();
                    try {
                        obj1.put("url","/rest/room");
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    socket.emit("get", obj1, new Ack() {
                        @Override
                        public void call(Object... args) {
                            Log.e("test", "GET");
                        }
                    });
                    Log.e("test", "CONNECT");
                }

            }).on("room", new Emitter.Listener()
            {
                @Override
                public void call(Object... args)
                {

                    Log.e("test", "ROOM");
                }
            });

但我有一个403原因URL需要身份验证。那么如何修改套接字头以放置Cookie并保持套接字和Web服务之间的会话?

1 个答案:

答案 0 :(得分:3)

以下是图书馆开发人员的答案:https://github.com/socketio/socket.io-client-java/issues/226

socket.io().on(Manager.EVENT_TRANSPORT, new Emitter.Listener() {
  @Override
  public void call(Object... args) {
    Transport transport = (Transport)args[0];

    transport.on(Transport.EVENT_REQUEST_HEADERS, new Emitter.Listener() {
      @Override
      public void call(Object... args) {
        @SuppressWarnings("unchecked")
        Map<String, List<String>> headers = (Map<String, List<String>>)args[0];
        // modify request headers
        headers.put("Cookie", Arrays.asList("foo=1;"));
      }
    });

    transport.on(Transport.EVENT_RESPONSE_HEADERS, new Emitter.Listener() {
      @Override
      public void call(Object... args) {
        @SuppressWarnings("unchecked")
        Map<String, List<String>> headers = (Map<String, List<String>>)args[0];
        // access response headers
        String cookie = headers.get("Set-Cookie").get(0);
      }
    });
  }
});