4

I use this library (https://github.com/socketio/socket.io-client-java) to connect my Android application with my Sails socket.io.

Here is the code I use:

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");
                }
            });

But I have a 403 cause URL need an authentication. So how can I modify socket headers to put the Cookie and keep the session between sockets and web services?

Cœur
  • 37,241
  • 25
  • 195
  • 267
jaumard
  • 8,202
  • 3
  • 40
  • 63

1 Answers1

5

Here is the answer from the dev of the library : 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);
      }
    });
  }
});
jaumard
  • 8,202
  • 3
  • 40
  • 63