androidmqtthivemq

How to use HiveMQ over websocket on Android


I am relatively new to MQTT and am trying to connect via a websocket in my Android app.

HiveMQ and Paho seem to be the most commonly used libraries, so I'll try my luck with those for now.

Unfortunately I got right at the first library and would need a hint on how to proceed, as the docs don't say anything about this unfortunately. With HiveMQ, it's not entirely clear to me how to connect via websocket, and how to customize my credentials/headers, because I need to add some custom header like "x-amz-customauthorizer-name" and some more.

This is my attempt without adding the user credentials:

val client = Mqtt3Client.builder()
    .identifier(UUID.randomUUID().toString())
    .serverAddress(InetSocketAddress(result.data.webSocketServer, 443))
    .sslWithDefaultConfig()
    .addConnectedListener { context: MqttClientConnectedContext? -> Log.e(javaClass.simpleName, "mqtt Here Connected Yay") }
    .addDisconnectedListener { context: MqttClientDisconnectedContext -> Log.e(javaClass.simpleName, "mqtt Disconnected: " + context.cause.message!!) }
    .buildAsync()

client.connect()

Solution

  • you just need to add the webSocketConfig to the builder, something like this:

            Mqtt3Client client = Mqtt3Client.builder()
                .identifier(UUID.randomUUID().toString())
                .serverAddress(new InetSocketAddress("localhost", 443))
                .sslWithDefaultConfig()
    this line-> .webSocketConfig(MqttWebSocketConfig.builder().subprotocol("mqtt").serverPath("/mqtt").build())
                .buildAsync();
    

    But I'm think you can't add custom headers yet, see https://github.com/hivemq/hivemq-mqtt-client/issues/457.

    Greetings,

    Michael