springboot2.3.0讀取配置檔案中文亂碼+阿里簡訊服務

yongwenxiu發表於2020-10-16

解決配置檔案讀取亂碼方案

1.配置中的中文轉為對應的ASCII碼(專案要在學校部署未採用

2.修改idea中的編碼(本地執行可以,放到伺服器還是亂碼
在這裡插入圖片描述

3.使用yml配置檔案進行配置。Spring Boot在讀取yaml配置檔案時使用的是UTF-8的編碼方式(習慣使用properties配置檔案未採用

4.Spring Boot註解讀取application.properties檔案時預設的是ISO_8859_1編碼導致亂碼,進行轉碼(專案中使用方案
new String(signName.getBytes(“ISO_8859_1”),“UTF-8”)

阿里簡訊服務jar

<dependency>
            <groupId>com.aliyun</groupId>
            <artifactId>aliyun-java-sdk-core</artifactId>
            <version>4.1.0</version>
        </dependency>

application.properties

#阿里簡訊配置
regionId=cn-hangzhou
accessKeyId=XXX
secret=XXX
domain=dysmsapi.aliyuncs.com
version=2017-05-25
signName=河南
#修改密碼驗證碼
xgmm=SMS_135230176
#登入確認驗證碼
dlqr=SMS_135230179

讀取配置檔案類

package com.xhkjedu.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.UnsupportedEncodingException;

/**
 * @author ywx
 * @classname ConfigKey
 * @description 讀取配置檔案類
 * @date 2020/10/16 9:19
 **/
@Component
public class ConfigKey {

    public static String regionId;
    public static String accessKeyId;
    public static String secret;
    public static String domain;
    public static String version;
    public static String signName;
    public static String xgmm;
    public static String dlqr;

    @Value("${regionId}")
    private void setRegionId(String regionId) {
        ConfigKey.regionId = regionId;
    }

    @Value("${accessKeyId}")
    private void setAccessKeyId(String accessKeyId) {
        ConfigKey.accessKeyId = accessKeyId;
    }

    @Value("${secret}")
    private void setSecret(String secret) {
        ConfigKey.secret = secret;
    }

    @Value("${domain}")
    private void setDomain(String domain) {
        ConfigKey.domain = domain;
    }

    @Value("${version}")
    private void setVersion(String version) {
        ConfigKey.version = version;
    }

    @Value("${signName}")
    private void setSignName(String signName) throws UnsupportedEncodingException {
        //Spring Boot註解讀取application.properties或者application-{profile}.properties檔案時預設的是ISO_8859_1編碼,中文會亂碼
        ConfigKey.signName = new String(signName.getBytes("ISO_8859_1"),"UTF-8");;
    }

    @Value("${xgmm}")
    private void setXgmm(String xgmm) {
        ConfigKey.xgmm = xgmm;
    }

    @Value("${dlqr}")
    private void setDlqr(String dlqr) {
        ConfigKey.dlqr = dlqr;
    }
}

package com.xhkjedu.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.UnsupportedEncodingException;

/**
 * @author ywx
 * @classname ConfigKey
 * @description 讀取配置檔案類
 * 在使用類中使用@Autowired自動裝配
 * 使用@Autowired的當前類也必須由spring容器託管(打@Coponent、@Controller、@Service 、@repository)
 * 不能使用new來初始化,否則會導致他的自動裝配的子類為null
 * @date 2020/10/16 9:19
 **/
@Component
public class ConfigKey {
    @Value("${regionId}")
    public String regionId;
    @Value("${accessKeyId}")
    public String accessKeyId;
    @Value("${secret}")
    public String secret;
    @Value("${domain}")
    public String domain;
    @Value("${version}")
    public String version;
//    @Value("${signName}")
    public String signName;
    @Value("${xgmm}")
    public String xgmm;
    @Value("${dlqr}")
    public String dlqr;

    @Value("${signName}")
    public void setSignName(String signName) throws UnsupportedEncodingException {
        this.signName = new String(signName.getBytes("ISO_8859_1"),"UTF-8");
    }
}

呼叫簡訊介面工具類

package com.xhkjedu.utils;

import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.xhkjedu.config.ConfigKey;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * @author ywx
 * @className SendSmsUtil
 * @description
 * @date 2020/5/7 17:15
 **/
@Slf4j
public class SendSmsUtil {
    /**
     * 阿里雲傳送簡訊
     * @Param [userPhone, templateCode]
     * @Author ywx
     * @Date 2020/5/7 17:47
     * @return void
     **/
    public static void sendMsg(String userPhone,String templateCode,Integer messageCode) {
        DefaultProfile profile = getDefaultProfile();
        IAcsClient client = new DefaultAcsClient(profile);

        CommonRequest request = getCommonRequest();
        request.putQueryParameter("PhoneNumbers", userPhone);
        request.setAction("SendSms");
        if ("xgmm".equals(templateCode)){//修改密碼驗證碼
            templateCode = ConfigKey.xgmm;
        } else if ("dlqr".equals(templateCode)){//登入確認驗證碼
            templateCode = ConfigKey.dlqr;
        }
        request.putQueryParameter("TemplateCode", templateCode);
        request.putQueryParameter("TemplateParam", "{'code':"+messageCode+"}");
        try {
            CommonResponse response = client.getCommonResponse(request);
            log.info(response.getData());
        } catch (ServerException e) {
            log.error(e.getMessage());
        } catch (ClientException e) {
            log.error(e.getMessage());
        }
    }

    private static CommonRequest getCommonRequest() {
        CommonRequest request = new CommonRequest();
        request.setMethod(MethodType.POST);
        request.setDomain(ConfigKey.domain);
        request.setVersion(ConfigKey.version);
        request.putQueryParameter("RegionId", ConfigKey.regionId);
        request.putQueryParameter("SignName", ConfigKey.signName);
        return request;
    }

    /**
     * 傳送記錄查詢
     * @Param [userPhone, sendDate]
     * @Author ywx
     * @Date 2020/10/15 16:31
     * @return java.lang.String
     **/
    @Autowired
    public static String querySendMsg(String userPhone,String sendDate) {
        DefaultProfile profile = getDefaultProfile();
        IAcsClient client = new DefaultAcsClient(profile);

        CommonRequest request = getCommonRequest();
        request.setAction("QuerySendDetails");
        request.putQueryParameter("PhoneNumber", userPhone);
        request.putQueryParameter("SendDate", sendDate);
        request.putQueryParameter("PageSize", "10");
        request.putQueryParameter("CurrentPage", "1");
        String result = null;
        try {
            CommonResponse response = client.getCommonResponse(request);
            result = response.getData();
        } catch (ServerException e) {
            e.printStackTrace();
        } catch (ClientException e) {
            e.printStackTrace();
        }
        return result;
    }

    private static DefaultProfile getDefaultProfile() {
        return DefaultProfile.getProfile(ConfigKey.regionId, ConfigKey.accessKeyId, ConfigKey.secret);
    }
}

package com.xhkjedu.utils;

import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.xhkjedu.config.ConfigKey;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * @author ywx
 * @className SendSmsUtil
 * @description
 * @date 2020/5/7 17:15
 **/
@Slf4j
public class SendSmsUtil {
    /**
     * 阿里雲傳送簡訊
     * @Param [userPhone, templateCode]
     * @Author ywx
     * @Date 2020/5/7 17:47
     * @return void
     **/
    public static void sendMsg(String userPhone,String templateCode,Integer messageCode,ConfigKey configKey) {
        DefaultProfile profile = getDefaultProfile(configKey);
        IAcsClient client = new DefaultAcsClient(profile);

        CommonRequest request = getCommonRequest(configKey);
        request.putQueryParameter("PhoneNumbers", userPhone);
        request.setAction("SendSms");
        if ("xgmm".equals(templateCode)){//修改密碼驗證碼
            templateCode = configKey.xgmm;
        } else if ("dlqr".equals(templateCode)){//登入確認驗證碼
            templateCode = configKey.dlqr;
        }
        request.putQueryParameter("TemplateCode", templateCode);
        request.putQueryParameter("TemplateParam", "{'code':"+messageCode+"}");
        try {
            CommonResponse response = client.getCommonResponse(request);
            log.info(response.getData());
        } catch (ServerException e) {
            log.error(e.getMessage());
        } catch (ClientException e) {
            log.error(e.getMessage());
        }
    }

    private static CommonRequest getCommonRequest(ConfigKey configKey) {
        CommonRequest request = new CommonRequest();
        request.setMethod(MethodType.POST);
        request.setDomain(configKey.domain);
        request.setVersion(configKey.version);
        request.putQueryParameter("RegionId", configKey.regionId);
        request.putQueryParameter("SignName", configKey.signName);
        return request;
    }

    /**
     * 傳送記錄查詢
     * @Param [userPhone, sendDate]
     * @Author ywx
     * @Date 2020/10/15 16:31
     * @return java.lang.String
     **/
    @Autowired
    public static String querySendMsg(String userPhone,String sendDate,ConfigKey configKey) {
        DefaultProfile profile = getDefaultProfile(configKey);
        IAcsClient client = new DefaultAcsClient(profile);

        CommonRequest request = getCommonRequest(configKey);
        request.setAction("QuerySendDetails");
        request.putQueryParameter("PhoneNumber", userPhone);
        request.putQueryParameter("SendDate", sendDate);
        request.putQueryParameter("PageSize", "10");
        request.putQueryParameter("CurrentPage", "1");
        String result = null;
        try {
            CommonResponse response = client.getCommonResponse(request);
            result = response.getData();
        } catch (ServerException e) {
            e.printStackTrace();
        } catch (ClientException e) {
            e.printStackTrace();
        }
        return result;
    }

    private static DefaultProfile getDefaultProfile(ConfigKey configKey) {
        return DefaultProfile.getProfile(configKey.regionId, configKey.accessKeyId, configKey.secret);
    }
}

##測試類

package com.xhkjedu;

import com.xhkjedu.config.ConfigKey;
import com.xhkjedu.utils.SendSmsUtil;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;

@SpringBootTest
class SchoolapiApplicationTests {
    @Test
    void contextLoads() {
        System.out.println(ConfigKey.signName);
        System.out.println(SendSmsUtil.querySendMsg("1314019XXXX","20201016"));
    }

}

package com.xhkjedu;

import com.xhkjedu.config.ConfigKey;
import com.xhkjedu.utils.SendSmsUtil;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;

@SpringBootTest
class SchoolapiApplicationTests {
	@Autowired
    private ConfigKey configKey;
    @Test
    void contextLoads() {
        System.out.println(configKey.signName);
        System.out.println(SendSmsUtil.querySendMsg("1314019XXXX","20201016",configKey));
    }

}

相關文章