Android mqtt连接阿里云MqttException (0) - java.net.UnknownHostException:

MqttException (0) - java.net.UnknownHostException: iot-06z00ga3tg8qyh3.mqtt.iothub.aliyuncs.com
W/System.err:     at org.eclipse.paho.client.mqttv3.internal.ExceptionHelper.createMqttException(ExceptionHelper.java:38)
        at org.eclipse.paho.client.mqttv3.internal.ClientComms$ConnectBG.run(ClientComms.java:715)
        at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:457)
        at java.util.concurrent.FutureTask.run(FutureTask.java:266)
        at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:301)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1162)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:636)
W/System.err:     at java.lang.Thread.run(Thread.java:764)
    Caused by: java.net.UnknownHostException: iot-06z00ga3tg8qyh3.mqtt.iothub.aliyuncs.com
        at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:178)
        at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:356)
        at java.net.Socket.connect(Socket.java:616)
W/System.err:     at org.eclipse.paho.client.mqttv3.internal.TCPNetworkModule.start(TCPNetworkModule.java:84)
        at org.eclipse.paho.client.mqttv3.internal.ClientComms$ConnectBG.run(ClientComms.java:701)
    	... 6 more

    看到这个异常的时候就已经猜测,分析主机地址错误导致的异常,那么很有可能是设备本身的网络的问题。但还是找到确切的解决方案,因为无从下手啊,只能说我计网还是没学到精髓。
    好吧,我只能说,往往最复杂的问题蕴含最简单道理,这个报错是因为没网,没错,就是没网,我调试安卓设备的时候,用的是虚拟机,所以一直连接不上。查阅许多资料后,还是没有谁遇到过这种东西,最后实在没法,试一把,用了真机去调试,好消息就是mqtt顺利连上了。所以我分析问题本身的变量,唉,网络联通问题。如果有朋友遇到同样的问题,可以试试看虚拟机的chrome能不能访问百度网页,能访问,说明网络是好的。不能的话,可以搜一下解决方案,我是通过取消代理解决的
在这里插入图片描述
既然朋友你找到这个问题,那么说明你也在解决Android利用mqtt连接阿里云的问题,我能说的帮助
1、阿里云文档有举例的代码
2、参考我的例子吧

mqtt.class

package 包名;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Context;
import android.nfc.Tag;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.orhanobut.logger.Logger;

import org.eclipse.paho.client.mqttv3.MqttException;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;


public class Mqtt extends AppCompatActivity {

    private static String topic = "/sys/idab2AcGde8/${deviceName}/thing/event/property/post_reply";
    String payload = "Hello Aliyun IoT";
    public static final String URL = "tcp://iot-06a00bc3de8fgh3.mqtt.iothub.aliyuncs.com:1883";//更改为自己创建产品的三元素
    private String userName = "merchandise&idab2AcGde8";//更改为自己创建产品的三元素
    private String password = "b123456feab23ef1ce123456bd78910a11b1213dec141516171cefaa71ae92b81b8";//更改为自己创建产品的三元素
    private String clientId = "idtk2AfGxz8.merchandise|securemode=2,signmethod=hmacsha256,timestamp=1235623431108|";//更改为自己创建产品的三元素

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.mqtt);

        EventBus.getDefault().register(this);
        //连接阿里云
        findViewById(R.id.btn_Connect).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        //boolean b = MqttManager.getInstance().createConnect(URL, userName, password, clientId);
                        //Logger.d("isConnected: " + b);
                    }
                }).start();
            }
        });
        //断开连接阿里云
        findViewById(R.id.btn_disConnect).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            MqttManager.getInstance().disConnect();
                        } catch (MqttException e) {

                        }
                    }
                }).start();
            }
        });
        //获取数据
//        findViewById(R.id.btn_getData).setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                new Thread(new Runnable() {
//                    @Override
//                    public void run() {
//                        MqttManager.getInstance().subscribe("/a1s8M2W04Q6/phone/user/ws", 0);
//                    }
//                }).start();
//            }
//        });
    }
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void showdata ( String event){
          JSONObject meg= JSON.parseObject(event);
          JSONObject meg2= JSON.parseObject(meg.get("params").toString());
          JSONObject meg3= JSON.parseObject(meg2.get("merchandise").toString());
          String kind= meg3.getString("kind");
          Log.e("kind",kind);
    };
    @Override
    protected void onStart() {
        super.onStart();

    }

    @Override
    protected void onResume() {
        super.onResume();

    }

    @Override
    protected void onPause() {
        super.onPause();

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}

MqttCallbackBus.class

package 包名;


import com.orhanobut.logger.Logger;

import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.greenrobot.eventbus.EventBus;

public class MqttCallbackBus implements MqttCallback {

    @Override
    public void connectionLost(Throwable cause) {
        //Logger.e(cause.getMessage());
        cause.printStackTrace();
    }

    @Override
    public void messageArrived(String topic, MqttMessage message) {
        Logger.d(topic + "====" + message.toString());
        String msg=message.toString().trim();
        EventBus.getDefault().post(msg);
    }

    @Override
    public void deliveryComplete(IMqttDeliveryToken token) {
    }


}

MqttManager.class

输出h123456都是为了看运行到哪个阶段出bug,可删

package 包名;

import com.orhanobut.logger.Logger;

import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.persist.MqttDefaultFilePersistence;

public class MqttManager {
    // 单例
    private static MqttManager mInstance = null;
    // 回调
    private MqttCallback mCallback;

    // Private instance variables
    private MqttClient client;
    private MqttConnectOptions conOpt;
    private boolean clean = true;

    private MqttManager() {
        mCallback = new MqttCallbackBus();
    }

    public static MqttManager getInstance() {
        if (null == mInstance) {
            mInstance = new MqttManager();
        }
        return mInstance;
    }

    /**
     * 释放单例, 及其所引用的资源
     */
    public static void release() {
        try {
            if (mInstance != null) {
                mInstance.disConnect();
                mInstance = null;
            }
        } catch (Exception e) {

        }
    }

    /**
     * 创建Mqtt 连接
     *
     * @param brokerUrl Mqtt服务器地址(tcp://xxxx:1863)
     * @param userName  用户名
     * @param password  密码
     * @param clientId  clientId
     * @return
     */
    public boolean createConnect(String brokerUrl, String userName, String password, String clientId) {
        boolean flag = false;
        String tmpDir = System.getProperty("java.io.tmpdir");
        MqttDefaultFilePersistence dataStore = new MqttDefaultFilePersistence(tmpDir);
        System.out.println("h1");
        try {
            // Construct the connection options object that contains connection parameters
            // such as cleanSession and LWT
            conOpt = new MqttConnectOptions();
            conOpt.setMqttVersion(MqttConnectOptions.MQTT_VERSION_3_1_1);
            conOpt.setCleanSession(clean);
            System.out.println("h2");
            if (password != null) {
                conOpt.setPassword(password.toCharArray());
            }
            if (userName != null) {
                conOpt.setUserName(userName);
            }

            // Construct an MQTT blocking mode client
            client = new MqttClient(brokerUrl, clientId, dataStore);

            // Set this wrapper as the callback handler
            client.setCallback(mCallback);
            System.out.println("h3");
            flag = doConnect();
        } catch (MqttException e) {
            Logger.e(e.getMessage());
        }

        return flag;
    }

    /**
     * 建立连接
     *
     * @return
     */
    public boolean doConnect() {
        boolean flag = false;
        if (client != null) {
            try {
                System.out.println("h4");
                client.connect(conOpt);
                System.out.println("Connected to " + client.getServerURI() + " with client ID " + client.getClientId());
                System.out.println("hhh");
                flag = true;
            } catch (MqttException e) {
                System.out.println("h5");
                e.printStackTrace();
                System.out.println("h6");
            }
        }
        return flag;
    }

    /**
     * Publish / send a message to an MQTT server
     *
     * @param topicName the name of the topic to publish to
     * @param qos       the quality of service to delivery the message at (0,1,2)
     * @param payload   the set of bytes to send to the MQTT server
     * @return boolean
     */
    public boolean publish(String topicName, int qos, byte[] payload) {

        boolean flag = false;

        if (client != null && client.isConnected()) {

            Logger.d("Publishing to topic \"" + topicName + "\" qos " + qos);

            // Create and configure a message
            MqttMessage message = new MqttMessage(payload);
            message.setQos(qos);

            // Send the message to the server, control is not returned until
            // it has been delivered to the server meeting the specified
            // quality of service.
            try {
                client.publish(topicName, message);
                flag = true;
            } catch (MqttException e) {

            }

        }

        return flag;
    }

    /**
     * Subscribe to a topic on an MQTT server
     * Once subscribed this method waits for the messages to arrive from the server
     * that match the subscription. It continues listening for messages until the enter key is
     * pressed.
     *
     * @param topicName to subscribe to (can be wild carded)
     * @param qos       the maximum quality of service to receive messages at for this subscription
     * @return boolean
     */
    public boolean subscribe(String topicName, int qos) {

        boolean flag = false;

        if (client != null && client.isConnected()) {
            // Subscribe to the requested topic
            // The QoS specified is the maximum level that messages will be sent to the client at.
            // For instance if QoS 1 is specified, any messages originally published at QoS 2 will
            // be downgraded to 1 when delivering to the client but messages published at 1 and 0
            // will be received at the same level they were published at.
            Logger.d("Subscribing to topic \"" + topicName + "\" qos " + qos);
            try {
                client.subscribe(topicName, qos);
                flag = true;
            } catch (MqttException e) {

            }
        }

        return flag;

    }

    /**
     * 取消连接
     *
     * @throws MqttException
     */
    public void disConnect() throws MqttException {
        if (client != null && client.isConnected()) {
            client.disconnect();
        }
    }
}

    最后,如果你还是无法解决,或是出现数不胜数的bug和难以找到答案的异常,请不要灰心丧气,总会有解决的时刻,只不过或早或晚,或是运气。相信每一刻努力的自己,因为我们同样在bug处丧失斗志,又前赴后继,总有人会在前方点亮一盏灯!听一首你喜欢的歌,放松一下心情,也许奇思妙想就在下一刻福至心灵,醍醐灌顶,拨云见日!

一路坎坷总要去经历他!

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值