使用springboot集成腾讯云短信服务,解决配置文件读取乱码问题

springboot集成腾讯云短信服务:

(1)导入依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
    <exclusions>
       <exclusion>
         <groupId>com.vaadin.external.google</groupId>
         <artifactId>android-json</artifactId>
       </exclusion>
        </exclusions>
</dependency>
<dependency>
    <groupId>com.github.qcloudsms</groupId>
    <artifactId>qcloudsms</artifactId>
    <version>1.0.6</version>
</dependency>

(2)将服务码等信息提取到全局配置文件

#短信应用 SDK AppID
tx.sms.appid=*************

#短信应用 SDK AppKey
tx.sms.appkey=***********

#签名参数使用的是`签名内容`
tx.sms.smsSign=草莓树下的思考公众号

#短信模板 ID,需要在短信应用中申请
tx.sms.templateId=*********

(3)提取工具类

@Component
public class SmsUtil {
    
    @Value("${tx.sms.appid}")
    private Integer appid;
    
    @Value("${tx.sms.appkey}")
    private String appkey;
    
    @Value("${tx.sms.smsSign}")
    private String smsSign;
   
 
    @Value("${tx.sms.templateId}")
    private Integer templateId;
    
    public void txSmsSend(String phoneNumber,ArrayList<String> params) {
        //7. 封装短信应用码
        SmsSingleSender ssender = new SmsSingleSender(appid,appkey);
        //地区,电话,模板ID,验证码,签名
            try {
                SmsSingleSenderResult result = ssender.sendWithParam(
                        "86", phoneNumber, templateId, params, smsSign, "", "");
                //输出一下返回值
                System.out.println(result);
            } catch (HTTPException | JSONException | IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }            
    }
}

(4)测试

@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes=PhoneApp.class)
public class Test {
    @Autowired
    private SmsUtil sms;
    
    @org.junit.Test
    public void test() {
        String phoneNumber = "17609584519";
        ArrayList<String> list = new ArrayList<>();
        list.add("赵丽颖");
        list.add("lyf");
        list.add("2019-08-13");
        
        sms.txSmsSend(phoneNumber, list);
    }
}

结果截图:

可以看到:短信内容中有一段信息是乱码的

原因分析:

  是由于在application.properties配置文件中读取 tx.sms.smsSign信息时,由于属性值是汉字,编码格式不一致,导致的

解决方案:

方式一:将  tx.sms.smsSign信息在程序中进行设置,如下:

private String smsSign = "草莓树下的思考公众号";

方式二:在application.properties中定义,但是在传参时要进行编码转换

application.properties配置文件

#签名参数使用的是`签名内容`
 tx.sms.smsSign=草莓树下的思考公众号

工具类:

@Value("${tx.sms.smsSign}") 
private String smsSign;
smsSign = new String(smsSign.getBytes("ISO8859-1"), "UTF-8");

最终结果截图:

谢谢支持!!!

猜你喜欢

转载自www.cnblogs.com/ncl-960301-success/p/11354366.html