Saturday, July 23, 2016

MQTT with SSL Connection Example

Using "setSSLProperties" in MqttConnectOptions we can easily configure SSL.
import java.util.Properties;

import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttMessage;

public class TestCon {
 public static void main(String[] args) {
  try {
   MqttClient client = new MqttClient("ssl://brocker_ip:8883", "testclient");
   MqttConnectOptions connectOptions = new MqttConnectOptions();
   connectOptions.setUserName("username");
   connectOptions.setPassword("password".toCharArray());
   Properties props = new Properties();
   props.setProperty("com.ibm.ssl.keyStore", "jksFilePath.jks");
   props.setProperty("com.ibm.ssl.keyStorePassword","jksPassword");
   connectOptions.setSSLProperties(props);
   client.connect(connectOptions);   
   MqttMessage  message = new MqttMessage();
   message.setPayload("test".getBytes());
   client.publish("topic", message);
   client.disconnect();   
  } catch (Exception e) {
   e.printStackTrace();
  }
  
 }
}

No comments:

Post a Comment

Total Pageviews

Translate