importjava.io.BufferedReader;importjava.io.DataOutputStream;importjava.io.InputStreamReader;importjava.net.HttpURLConnection;importjava.net.URL;importjava.net.URLEncoder;importjava.security.MessageDigest;importorg.apache.commons.logging.Log;importorg.apache.commons.logging.LogFactory;importnet.sf.json.JSONObject;/*** 信信客短信工具类*/
public class XxkSmsCore extendsSmsCore {private static Log logger = LogFactory.getLog(XxkSmsCore.class);//转码
public String encode(String input) throwsException {return URLEncoder.encode(input, "UTF-8");
}//计算 MD5 值
public static String md5(String input) throwsException {byte[] digest = MessageDigest.getInstance("MD5").digest(input.getBytes("UTF-8"));
StringBuffer sb= newStringBuffer();for (int i = 0; i < digest.length; i++) {
sb.append(String.format("%02x", Integer.valueOf(digest[i] & 0xFF)));
}returnsb.toString();
}//发起 POST 请求
public String post(String url, String data) throwsException {//打开连接
HttpURLConnection conn = (HttpURLConnection) (newURL(url)).openConnection();
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setRequestMethod("POST");
conn.setUseCaches(false);
conn.connect();//输出参数
DataOutputStream dos = newDataOutputStream(conn.getOutputStream());
dos.writeBytes(data);
dos.flush();
dos.close();//读取响应
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
String line=br.readLine();
br.close();//关闭连接
conn.disconnect();returnline;
}/*** 短信发送接口
*
*@paramsmsTemplateCode
* 短信模板编号
*@paramsmsParam
* 短信模板变量 {\"code\":\"" + Math.random() + "\"}
*@paramrecNum
* 接收号码
*@paramrecNum
* 短信签名
*@throwsException*/
public ResultUtil send(SmsParam smsParam) throwsException {
ResultUtil rs=ResultUtil.fail();//参数
String url = "http://www.xinxinke.com/api/send";
String sign= md5(smsParam.getAppId() + smsParam.getAppKey() +smsParam.getMobile());//拼接
StringBuffer data = newStringBuffer();
data.append("").append("dev_id").append("=").append(encode(smsParam.getAppId()));
data.append("&").append("sign").append("=").append(encode(sign));
data.append("&").append("sms_template_code").append("=").append(encode(smsParam.getSmsTemplateCode()));
data.append("&").append("sms_param").append("=").append(encode(smsParam.getContent()));
data.append("&").append("rec_num").append("=").append(encode(smsParam.getMobile()));
data.append("&").append("sms_sign").append("=").append(encode(smsParam.getSignName()));
logger.info("信信客短信发送参数,手机号码:" + smsParam.getMobile() + ",验证码:" + smsParam.getContent() + ",短信签名:" + smsParam.getSignName() + ",短信模板:" +smsParam.getSmsTemplateCode());
String response=post(url, data.toString());
logger.info("信信客短信发送响应,response:" +response);
JSONObject jsonObject=JSONObject.fromObject(response);
String code= jsonObject.getString("code");if ("25010".equals(code)) {return ResultUtil.ok().set("code", "200").set("msg", "发送成功!");
}return rs.set("msg", jsonObject.getString("data"));
}
}