首页 > 解决方案 > Azure IoT Hub MQTT 失败(无 SDK)

问题描述

我正在尝试使用 Microsoft Azure IOT Hub( MQTT) 将我的Java客户端设备连接到 IOT Hub(不带SDK)。我根据需要创建了设备和SAS使用TTL。我正在使用 paho 客户端连接到 IoT 中心。我正在低于错误。SAS我从 IoT 中心工具创建的令牌,有效期为 5 小时。

未授权在 org.eclipse.paho.client.mqttv3.internal.ClientState.notifyReceivedAck(ClientState.java 的 org.eclipse.paho.client.mqttv3.internal.ExceptionHelper.createMqttException(ExceptionHelper.java:28) 连接 (5) :1040) at org.eclipse.paho.client.mqttv3.internal.CommsReceiver.run(CommsReceiver.java:151) at java.lang.Thread.run(Unknown Source)

下面是我正在尝试的代码:

String deviceId = "mqqdirectdevice1";     
          String brokerUri = "ssl://xxxxx:8883";
          String clientId = deviceId;
          System.out.println( "Connecting to " + brokerUri +" as "+clientId);

          MqttAsyncClient client = null;
          try {           
              String sasToken="SharedAccessSignature sr=xxxxxxx.azure-devices.net%2Fdevices%2Fmqqdirectdevice1&sig=iJ3jacTNMdyyhIrQueBN5X6uEqURYCKfa5Z63ePKDRs%3D&se=1600335545";
              client = new MqttAsyncClient( brokerUri, clientId,new MemoryPersistence());
              
            if ( client != null ) {             
              MqttConnectOptions options = new MqttConnectOptions();                          
              client.setCallback( new AzureCallback() );             
              options.setUserName("xxxxxx.net/mqqdirectdevice1?api-version=2018-06-30");
              options.setPassword(sasToken.toCharArray());
             // options.setPassword(sasToken.toCharArray());
              options.setKeepAliveInterval(230);
              options.setCleanSession(false);
              options.setMqttVersion(4);              
              IMqttToken token=client.connect( options );
              token.waitForCompletion(60 * 1000);
              System.out.println("Sent MQTT CONNECT packet was acknowledged");
              if ( client.isConnected() ) {
                System.out.println( "Success!" );
              } else {
                System.out.println( "Could not connect to Azure IoT hub, timed-out" );
              }
            }
          } catch ( MqttException) {
            //client.getDebug().dumpBaseDebug();
            e.printStackTrace();
          } finally {
            if ( client != null ) {
              try {
                client.disconnect();
              } catch ( MqttException ignore ) {}
            }
          }

标签: mqttazure-iot-hub

解决方案


在您的示例中,您使用以下用户名:

xxxxxx.net/mqqdirectdevice1?api-version=2018-06-30

格式略有不同,您目前在问号前缺少正斜杠。正确的格式是:

xxxxxx.net/mqqdirectdevice1/?api-version=2018-06-30

我测试了一下,使用格式不正确的用户名无法建立MQTT连接。


推荐阅读