socket.io-java-client cookies / custom headers

2019-05-31 14:36发布

I'm doing a mobile app for a website and they use Socket.io and Websocket to comunicate.

I'm using socket.io-java-client on Android to connect to the Socket.io server, the problem is, i don't know how to set custom headers / cookies with it.

here is how the code looks like:

    public void runIO(){
        try {
            SocketIO socket = new SocketIO("http://192.168.1.60:1337");
            socket.connect(new IOCallback() {
                @Override
                public void onMessage(JSONObject json, IOAcknowledge ack) {
                    try {
                        System.out.println("Server said:" + json.toString(2));
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }

                @Override
                public void onMessage(String data, IOAcknowledge ack) {
                    System.out.println("Server said: " + data);
                }

                @Override
                public void onError(SocketIOException socketIOException) {
                    System.out.println("an Error occured");
                    socketIOException.printStackTrace();
                }

                @Override
                public void onDisconnect() {
                    System.out.println("Connection terminated.");
                }

                @Override
                public void onConnect() {
                    System.out.println("Connection established");
                }

                @Override
                public void on(String event, IOAcknowledge ack, Object... args) {
                    System.out.println("Server triggered event '" + event + "'");
                }
            });

            // This line is cached until the connection is establisched.
            socket.send("Hello Server!");
        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

1条回答
啃猪蹄的小仙女
2楼-- · 2019-05-31 15:23

In fact there are simple functions that can be used to set headers before connection:

addHeader(String key, String value) and setHeaders(Properties headers)

You can also use SocketIO(final String url, Properties headers) (instead of SocketIO(final String url) that i was using):

// Haeader Properties initiation
    private Properties headers = new Properties();

and then for exemple to set cookies:

headers.setProperty("Cookie","key=data;key2=data2");

Finally when connecting replace

this.socket = new SocketIO(val);

by

this.socket = new SocketIO(val,this.headers);
查看更多
登录 后发表回答