socketio / engine.io-client-java

Engine.IO Client Library for Java
http://socketio.github.io/engine.io-client-java
Other
360 stars 167 forks source link

How to Send Custom Header in Android #97

Closed ghost closed 3 years ago

ghost commented 6 years ago

Convert this code in JAVA

iOS Swift code let manager = SocketManager(socketURL: URL(string: "http://2de0c832.ngrok.io/")!, config: [.log(true), .compress, .extraHeaders(["Authorization": "Bearer \(Defaults[.authToken])"])])

juniorfrogie commented 6 years ago

Do you find way to do it yet? I'm stuck at this too.

KonstantinBerkow commented 6 years ago

Use OkHttpClient with Interceptor, and add your custom headers there, like this:

final OkHttpClient httpClient = new OkHttpClient.Builder()
        .addNetworkInterceptor(new CustomHeaderInterceptor())
        .build();

Then create socket like this:

final URI socketUri = // ...

final IO.Options options = new IO.Options();
options.webSocketFactory = httpClient;
options.callFactory = httpClient;

final Socket socket = IO.socket(socketUri, options);
hasankucuk commented 5 years ago

@KonstantinBerkow Thanks. After five hours of work, the problem was solved. :) 👍

darrachequesne commented 3 years ago

According to the README, you can add a custom header with:

socket.on(Socket.EVENT_TRANSPORT, new Emitter.listener() {
  @Override
  public void call(Object... args) {
    // Called on a new transport created.
    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];
        headers.put("Authorization", Arrays.asList("Bearer xxxx"));
      }
    });
  }
});

But based on the number of questions around this, I think it might make sense to add a headers map in the Socket.Options object.

darrachequesne commented 3 years ago

Closed by https://github.com/socketio/engine.io-client-java/commit/dfe65e3b3b5eab4c3fddb9dfbf53d684fe461043.