MQTT是物聯(lián)網(wǎng)時(shí)代的基礎(chǔ)通訊協(xié)議口蝠。Paho Mqtt Client是android應(yīng)用開發(fā)中廣泛使用的Mqtt Client庫飘诗。為了確保通訊安全专挪,通常會(huì)使用SSL來進(jìn)行通訊的加密授霸。
Paho Mqtt Client官網(wǎng)上并沒有詳細(xì)說明解釋如何建立SSL/TLS連接裂允,下面記錄一下里烦。
1 生成證書
網(wǎng)上的說明很多凿蒜,重點(diǎn)是要轉(zhuǎn)換成BKS格式的證書。
我參考的是下面的鏈接:http://www.steves-internet-guide.com/mosquitto-tls/
轉(zhuǎn)換BKS格式的步驟
- 到https://www.bouncycastle.org/latest_releases.html下載bcprov-jdk15on-159.jar
- 將jar放到JDK或者JRE目錄下的/lib/ext中
- 運(yùn)行命令
keytool -importcert -keystore mqtt_server.bks -file ca.crt -storetype BKS -providerclass org.bouncycastle.jce.provider.BouncyCastleProvider- mqtt_server.bks,要生成BKS格式的證書
- ca.crt是按照#1步驟生成的證書
- 如果碰到j(luò)ava.lang.ClassNotFoundException: org.bouncycastle.jce.provider.BouncyCastleProvider的錯(cuò)誤胁黑,那就是bcprov-jdk15on-159.jar沒有放到正確的目錄去废封。解決方法:首先確認(rèn)一下使用的keytool是在JDK還是JRE的目錄下,如果keytool是在jdk下丧蘸,就將bcprov-jdk15on-159.jar復(fù)制jdk的lib/ext下漂洋,如果是在jre的下,就復(fù)制到JRE的lib/ext目錄下力喷。
- 生成的BKS證書要放到Android項(xiàng)目的res/raw下
2 引用Paho Mqtt Client庫
按照Paho Mqtt Client在github上的說明就可以完成刽漂,別忘了在AndroidManifest.xml中聲明mqttservice。
<service android:name="org.eclipse.paho.android.service.MqttService">
</service>
3 具體的代碼
直接上代碼
private void doStartMqttClient() {
if (mMqttClient == null) {
initMqttClient();
}
mMqttClient.setCallback(mCallback);
try {
mMqttClient.connect(mMqttConnectionOptions, null, mqttActionListener);
} catch (MqttException e) {
e.printStackTrace();
}
}
private void initMqttClient() {
mMqttClient = new MqttAndroidClient(this.getApplicationContext(),
Constants.SSL_URL, getClientId());
mMqttConnectionOptions = new MqttConnectOptions();
mMqttConnectionOptions.setCleanSession(true);
mMqttConnectionOptions.setAutomaticReconnect(false);
mMqttConnectionOptions.setUserName(Constants.USER_NAME);
mMqttConnectionOptions.setPassword(Constants.PASSWORD.toCharArray());
SocketFactory socketFactory = getSocketFactory();
mMqttConnectionOptions.setSocketFactory(socketFactory);
}
private SocketFactory getSocketFactory() {
try {
SSLContext context;
KeyStore ts = KeyStore.getInstance("BKS");
ts.load(getResources().openRawResource(R.raw.mqtt_server),
Constants.CACRT_PASSWORD.toCharArray());
TrustManagerFactory tmf = TrustManagerFactory.getInstance("X509");
tmf.init(ts);
TrustManager[] tm = tmf.getTrustManagers();
context = SSLContext.getInstance("TLS");
context.init(null, tm, null);
return context.getSocketFactory();
} catch (Exception e) {
Log.e(TAG, "", e);
notifyActivity(e.getLocalizedMessage());
return null;
}
}
MqttCallbackExtended mCallback = new MqttCallbackExtended() {
@Override
public void connectComplete(boolean reconnect, String serverURI) {
notifyActivity("連接成功冗懦!");
}
@Override
public void connectionLost(Throwable cause) {
notifyActivity("connectionLost");
}
@Override
public void messageArrived(String topic, MqttMessage message) {
notifyActivity("收到消息爽冕!");
}
@Override
public void deliveryComplete(IMqttDeliveryToken token) {
notifyActivity("發(fā)送完成!");
}
};
private static class MqttActionListener implements IMqttActionListener {
WeakReference<ModuleService> mService;
MqttActionListener(ModuleService service) {
mService = new WeakReference<>(service);
}
@Override
public void onSuccess(IMqttToken asyncActionToken) {
ModuleService service = mService.get();
if (service != null) {
service.setStatus(STATUS_CONNECTED);
service.doSubscribeTopic();
service.mHandler.sendEmptyMessage(MSG_ONLINE);
}
}
@Override
public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
ModuleService service = mService.get();
if (service != null) {
service.setStatus(STATUS_CONNECT_FAIL);
service.mHandler.sendEmptyMessage(MSG_CONN_FAIL);
Log.e(TAG, "", exception);
service.notifyActivity(exception.getLocalizedMessage());
}
}
}