JAVA 手机短信发送

一共需要四个类


ChuangLanSmsUtil.java

package com.pp.global.sms;


import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;


/**
 *
 * @author tianyh
 * @Description:HTTP 请求
 */
public class ChuangLanSmsUtil {


    /**
     *
     * @author tianyh
     * @Description
     * @param path
     * @param postContent
     * @return String
     * @throws
     */
    public static String sendSmsByPost(String path, String postContent) {
        URL url = null;
        try {
            url = new URL(path);
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.setRequestMethod("POST");// 提交模式
            httpURLConnection.setConnectTimeout(10000);//连接超时 单位毫秒
            httpURLConnection.setReadTimeout(10000);//读取超时 单位毫秒
            // 发送POST请求必须设置如下两行
            httpURLConnection.setDoOutput(true);
            httpURLConnection.setDoInput(true);
            httpURLConnection.setRequestProperty("Charset", "UTF-8");
            httpURLConnection.setRequestProperty("Content-Type", "application/json");


            httpURLConnection.connect();
            OutputStream os=httpURLConnection.getOutputStream();
            os.write(postContent.getBytes("UTF-8"));
            os.flush();


            StringBuilder sb = new StringBuilder();
            int httpRspCode = httpURLConnection.getResponseCode();
            if (httpRspCode == HttpURLConnection.HTTP_OK) {
                // 开始获取数据
                BufferedReader br = new BufferedReader(
                        new InputStreamReader(httpURLConnection.getInputStream(), "utf-8"));
                String line = null;
                while ((line = br.readLine()) != null) {
                    sb.append(line);
                }
                br.close();
                return sb.toString();


            }


        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


}


SmsSend.java

package com.pp.global.sms;


import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
import net.sf.json.util.PropertyFilter;


import java.util.Random;


public class SmsSend {
    private static final String CHARSET = "utf-8";
    // 用户平台API账号(非登录账号,示例:N1234567)
    private static String ACCOUNT = "";  //该处输入平台账号


    // 用户平台API密码(非登录密码)
    private static String PSWD = ""; //该处输入平台密码


  private static  String SMSURL = "http://smssh1.253.com/msg/send/json";
    /**
     * 发送验证码消息
     */
    public static SmsSendResponse sendVerificationCodeMessage(String phone){


        Random random = new Random();


        // 短信内容
        String msg = "【253云通讯】你好,你的验证码是";
        String verificationCode="";
        for (int i=0;i<6;i++){
            verificationCode+=String.valueOf(random.nextInt(10));
        }
        msg+=verificationCode;


        //状态报告
        String report= "true";


        SmsSendRequest smsSingleRequest = new SmsSendRequest(ACCOUNT, PSWD, msg, phone,report);


        JsonConfig jsonConfig = new JsonConfig();
        PropertyFilter filter = new PropertyFilter() {
            public boolean apply(Object object, String fieldName, Object fieldValue) {
                return null == fieldValue;
            }
        };
        jsonConfig.setJsonPropertyFilter(filter);
        String requestJson = String.valueOf(JSONObject.fromObject(smsSingleRequest,jsonConfig));
        System.out.println(requestJson);
        System.out.println("before request string is: " + requestJson);


        //请求地址请登录253云通讯自助通平台查看或者询问您的商务负责人获取


        String response = ChuangLanSmsUtil.sendSmsByPost(SMSURL, requestJson);


        System.out.println("response after request result is :" + response);


        SmsSendResponse smsSingleResponse = (SmsSendResponse) JSONObject.toBean(JSONObject.fromObject(response),SmsSendResponse.class);
        smsSingleResponse.setVerificationCode(verificationCode);
        System.out.println("response  toString is :" + smsSingleResponse);
        return smsSingleResponse;
    }


}


SmsSendRequest.java

package com.pp.global.sms;
/**
 * 
 * @author tianyh 
 * @Description:普通短信发送实体类
 */
public class SmsSendRequest {
/**
* 用户账号,必填
*/
private String account;
/**
* 用户密码,必填
*/
private String password;
/**
* 短信内容。长度不能超过536个字符,必填
*/
private String msg;
/**
* 机号码。多个手机号码使用英文逗号分隔,必填
*/
private String phone;


/**
* 定时发送短信时间。格式为yyyyMMddHHmm,值小于或等于当前时间则立即发送,默认立即发送,选填
*/
private String sendtime;
/**
* 是否需要状态报告(默认false),选填
*/
private String report;
/**
* 下发短信号码扩展码,纯数字,建议1-3位,选填
*/
private String extend;
/**
* 该条短信在您业务系统内的ID,如订单号或者短信发送记录流水号,选填
*/
private String uid;

public SmsSendRequest() {

}
public SmsSendRequest(String account, String password, String msg, String phone) {
super();
this.account = account;
this.password = password;
this.msg = msg;
this.phone = phone;
}
public SmsSendRequest(String account, String password, String msg, String phone, String report) {
super();
this.account = account;
this.password = password;
this.msg = msg;
this.phone = phone;
this.report=report;
}

public SmsSendRequest(String account, String password, String msg, String phone, String report, String sendtime) {
super();
this.account = account;
this.password = password;
this.msg = msg;
this.phone = phone;
this.sendtime=sendtime;
this.report=report;
}
public SmsSendRequest(String account, String password, String msg, String phone, String sendtime, String report, String uid) {
super();
this.account = account;
this.password = password;
this.msg = msg;
this.phone = phone;
this.sendtime=sendtime;
this.report=report;
this.uid=uid;
}
public String getAccount() {
return account;
}
public void setAccount(String account) {
this.account = account;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {

this.msg = msg;


SmsSendResponse.java


package com.pp.global.sms;
/**
 * 
 * @author tianyh 
 * @Description:普通短信发送响应实体类
 */
public class SmsSendResponse {


/**
* 验证码
*/
private String VerificationCode;


public String getVerificationCode() {
return VerificationCode;
}


public void setVerificationCode(String verificationCode) {
VerificationCode = verificationCode;
}


/**
* 响应时间
*/
private String time;
/**
* 消息id
*/
private String msgId;
/**
* 状态码说明(成功返回空)
*/
private String errorMsg;
/**
* 状态码(详细参考提交响应状态码)
*/
private String code;
public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}
public String getMsgId() {
return msgId;
}
public void setMsgId(String msgId) {
this.msgId = msgId;
}
public String getErrorMsg() {
return errorMsg;
}
public void setErrorMsg(String errorMsg) {
this.errorMsg = errorMsg;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
@Override
public String toString() {
return "SmsSingleResponse [time=" + time + ", msgId=" + msgId + ", errorMsg=" + errorMsg + ", code=" + code
+ "]";
}



}


调用:

SmsSendResponse smsSendResponse = SmsSend.sendVerificationCodeMessage(username);//发送验证码

String verificationCode = smsSendResponse.getVerificationCode();//得到验证码字符串

RedisCache.putCacheWithExpireTime(username, verificationCode, (long) 360);//将手机验证码存入redis key为username

猜你喜欢

转载自blog.csdn.net/q6936575/article/details/80564598