1.通过java获取emqx的连接clientid列表
注:通过代码获取emqx服务器连接的客户端列表信息,java代码实现clientid列表如下:
private String username = "emqx账号";
private String password = "emqx密码";
public String fetchClientList() throws Exception {
String EMQX_API_URL = "emqx后台clientid列表url";
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpGet httpGet = new HttpGet(EMQX_API_URL);
httpGet.setHeader("Authorization", "Basic " + Base64.getEncoder()
.encodeToString((username + ":" + password).getBytes()));
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
String response = EntityUtils.toString(httpEntity, "UTF-8");
return response;
}
2.删除某个clientid连接
删除地址为:http://127.0.0.1:18083/api/v4/clients/clientid_000001
public ResultDTO deleteClientId(String clientid){
log.info("deleteClientId 设备禁用,下行指令剔除原mqtt的clientid连接,入参clientid: {}", clientid);
try {
clientid = URLEncoder.encode(clientid,"UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
return ResultDTO.getFailure();
}
// 这里拼接处要删除clientid 地址。例:http://127.0.0.1:18083/api/v4/clients/clientid_000001
String url = String.format(ConstantConfig.MQTT_DASHBOARD_URL_STR, ConstantConfig.getServerConfig().getProperty(ConstantConfig.MQTT_DASHBOARD_URL).trim(), clientid );
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpDelete httpDelete = new HttpDelete(url);
RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(35000).setConnectionRequestTimeout(35000).setSocketTimeout(60000).build();
httpDelete.setConfig(requestConfig);
// 这里emqx web的登录名密码。例:admin:public
String authString = ConstantConfig.getServerConfig().getProperty(ConstantConfig.MQTT_DASHBOARD_USER).trim()+":"+ConstantConfig.getServerConfig().getProperty(ConstantConfig.MQTT_DASHBOARD_PASSWORD).trim();
byte[] authEncBytes = Base64.encodeBase64(authString.getBytes());
String authStringEnc = new String(authEncBytes);
httpDelete.setHeader("Authorization", "Basic " + authStringEnc);
httpDelete.setHeader("Content-type", "application/json");
httpDelete.setHeader("DataEncoding", "UTF-8");
CloseableHttpResponse httpResponse = null;
try {
// 通过http请求进行访问。
httpResponse = httpClient.execute(httpDelete);
HttpEntity entity = httpResponse.getEntity();
// 获得删除结果
String result = EntityUtils.toString(entity);
} catch (ClientProtocolException e) {
e.printStackTrace();
return ResultDTO.getFailure();
} catch (IOException e) {
e.printStackTrace();
return ResultDTO.getFailure();
} finally {
if (httpResponse != null) {
try {
httpResponse.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (null != httpClient) {
try {
httpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return ResultDTO.getSuccess();
}