SmsChineseHttpClient.java 2.37 KB
package com.diligrp.assistant.sms.client;

import com.diligrp.assistant.shared.ErrorCode;
import com.diligrp.assistant.shared.service.ServiceEndpointSupport;
import com.diligrp.assistant.sms.exception.SmsServiceException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class SmsChineseHttpClient extends ServiceEndpointSupport {

    private static final Logger LOGGER = LoggerFactory.getLogger(SmsChineseHttpClient.class);

    /**
     * 接口地址
     */
    private String uri;

    /**
     * 用户名
     */
    private String uid;

    /**
     * 短信密钥
     */
    private String secretKey;

    public SmsChineseHttpClient(String uri, String uid, String secretKey) {
        this.uri = uri;
        this.uid = uid;
        this.secretKey = secretKey;
    }

    public String sendSmsMessage(String telephone, String message, String signature) {
        HttpParam[] params = new HttpParam[4];
        params[0] = HttpParam.create("Uid", uid);
        params[1] = HttpParam.create("Key", secretKey);
        params[2] = HttpParam.create("smsMob", telephone);
        params[3] = HttpParam.create("smsText", String.format("【%s】%s", signature, message));
        HttpResult result = send(uri, params);
        if (result.statusCode != 200) {
            throw new SmsServiceException(ErrorCode.SERVICE_ACCESS_ERROR, "调用网建短信服务失败");
        }

        int code = Integer.parseInt(result.responseText);
        if (code <= 0) {
            LOGGER.error("发送短信失败, 错误码: {}", code);
            throw new SmsServiceException(ErrorCode.SERVICE_ACCESS_ERROR, "发送短信失败, " + errorMessage(code));
        }
        return null;
    }

    private String errorMessage(int code) {
        switch (code) {
            case -1:
            case -11:
                return "账号不存在或被禁用";
            case -2:
            case -21:
                return "接口密钥错误";
            case -3:
                return "短信数量不足";
            case -4:
            case -41:
                return "手机号码为空或格式不正确";
            case -14:
            case -42:
                return "短信内容为空或出现非法字符";
            case -51:
            case -52:
                return "短信签名太长或格式不正确";
            default:
                return "未知错误";
        }
    }
}