废话不多说,直接上代码

实体类 

@Data
public class MQTTRequest {
    private String ClientId;
    private String UserName;
    private String Password;
}

工具类

package com.example.huaweiyun.utils;

import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;

import static com.example.huaweiyun.utils.HmacSha256Example.calculateHmacSha256;

public class MQTTGen {

    private final String deviceId = "设备ID";

    private final String secret = "设备密码";

    private final Integer type = 0;//设备身份标识类型

    private final String sign = "0";//密码签名类型

    private final String time = "2025/05/16 17:53:01 GMT+08:00";//注册机器的时间戳

    public MQTTRequest gen() {
        MQTTRequest request = new MQTTRequest();
        // 1. 定义解析格式
        DateTimeFormatter parser = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss 'GMT'xxx");

        // 2. 解析为 OffsetDateTime(带时区)
        OffsetDateTime odt = OffsetDateTime.parse(time, parser);

        // 3. 转换为 UTC 时间(减去 8 小时)
        OffsetDateTime utcTime = odt.withOffsetSameInstant(ZoneOffset.UTC);

        // 4. 格式化为 "yyyyMMddHH"
        String result = utcTime.format(DateTimeFormatter.ofPattern("yyyyMMddHH"));

        System.out.println(result);
        String client = deviceId + '_' + type + '_' + sign + '_' + result;
        String password;
        try {
            //H256加密
            password = calculateHmacSha256(secret, result);
            request.setClientId(client);
            request.setUserName(deviceId);
            request.setPassword(password);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return request;
    }

    public static void main(String[] args) {
        MQTTGen mQTTGen = new MQTTGen();
        MQTTRequest gen = mQTTGen.gen();
        System.out.println(gen);
    }
}

如果本文章对您有所帮助,还请给个免费的赞和关注,共勉!

Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐