Skip to content

Instantly share code, notes, and snippets.

@0532
Created April 2, 2015 13:58
Show Gist options
  • Save 0532/6c7c3d0e97a96b770aaf to your computer and use it in GitHub Desktop.
Save 0532/6c7c3d0e97a96b770aaf to your computer and use it in GitHub Desktop.
send telephone message
/*
* Copyright 2010 by LongTop Corporation.
*
* All rights reserved.
*
* This software is the confidential and proprietary information of
* LongTop Corporation ("Confidential Information"). You
* shall not disclose such Confidential Information and shall use
* it only in accordance with the terms of the license agreement
* you entered into with LongTop.
*
*/
package card.sms;
import java.util.regex.Pattern;
/**
* 手机短讯模板类.
*/
public class SmsTemplate {
// 开卡信息
public static final String TPL_SMS_OPEN_CARD = "欢迎您成为海尔卡用户!您的卡号是{0},预存金额{2}元," +
"使用有效期{3},请牢记密码并在有效期限内使用,此卡仅能在海尔专卖店使用。";
public static final String TPL_SMS_CHANGE_PWD = "您的海尔卡{0}密码已变更,请牢记新密码并在有效期限内使用,此卡仅能在海尔专卖店使用。";
public static final String TPL_SMS_CHANGE_INFO = "您的海尔卡{0}资料已变更,请在有效期内使用此卡。";
public static final String TPL_SMS_CONSUME_INFO = "您的海尔卡{0}消费成功,消费金额{1}元,卡余额{2}元。";
public static final String TPL_SMS_REFUND_INFO = "您的海尔卡{0}退费成功,退费金额{1}元,卡余额{2}元。";
public static final String TPL_SMS_LOST = "您的海尔卡{0}已挂失,暂时无法使用,请解除挂失后再使用此卡。";
public static final String TPL_SMS_UNLOST = "您的海尔卡{0}已解除挂失,请在有效期内使用此卡。";
public static final String TPL_SMS_CANCEL = "您的海尔卡{0}已作废,此卡已不能使用。";
public static final String TPL_SMS_CHANGE_CARD = "您的海尔卡{0}信息已复制到新卡{1},请在有效期内使用新卡。";
public static final String TPL_SMS_RANDOM_CODE = "您的海尔卡{0}的随机验证码为{1},请准确输入并及时重置密码。";
/**
* 占位符正则表达式, Pattern
*/
private static final Pattern placeholder = Pattern.compile("\\{[0-9]+\\}");
/**
* 短讯内容构建类, 或者直接采用MessageFormat类
*
* @param tpl 模板内容
* @param values 短讯值
* @return
*/
public static String buildSmsContent(String tpl, String[] values) {
// return MessageFormat.format(tpl, values);
//FIXME 不采用MessageFormat;
String[] arr = placeholder.split(tpl);
StringBuilder builder = new StringBuilder();
int valLen = 0;
if (values != null) {
valLen = values.length;
}
for (int i = 0, n = arr.length; i < n; i++) {
builder.append(arr[i]);
if (i < valLen) {
builder.append(values[i]);
}
}
return builder.toString();
}
public static void main(String[] args) {
System.out.println(buildSmsContent(TPL_SMS_OPEN_CARD, new String[]{"6238dhfh", "s'fhskdjfsdk"}));
}
}
/*
* Copyright 2009 by LongTop Corporation.
*
* All rights reserved.
*
* This software is the confidential and proprietary information of
* LongTop Corporation ("Confidential Information"). You
* shall not disclose such Confidential Information and shall use
* it only in accordance with the terms of the license agreement
* you entered into with LongTop.
*
*/
package card.sms;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.ByteArrayRequestEntity;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;
/**
* 发送短信的工具类
*/
public class SmsTool {
//从配置文件中获取发送短信的配置.
private static String OPERID = "cwgs";
private static String OPERPASS = "cwgs";
private static String SMS_SEND_URL = "http://10.128.3.99:8080/httpapi/submitMessage";
protected final static Log logger = LogFactory.getLog(SmsTool.class);
protected final static String PREFIX = "<?xml version=\"1.0\" encoding=\"GBK\"?>\r\n<CoreSMS><OperID>" + OPERID
+ "</OperID><OperPass>" + OPERPASS + "</OperPass><Action>Submit</Action>"
+ "<Category>0</Category><Body><SendTime></SendTime><AppendID></AppendID>";
protected final static String SUFFIX = "</Body></CoreSMS>";
//重复次数
private final static int REPEAT_NUM = 3;
private static String buildMessage(String cellphone, String message) {
StringBuilder builder = new StringBuilder(PREFIX);
builder.append("<Message>");
builder.append("<DesMobile>").append(cellphone).append("</DesMobile>");
builder.append("<Content>").append(message).append("</Content>");
builder.append("</Message>");
builder.append(SUFFIX);
return builder.toString();
}
private static boolean executeSend(String msg) throws HttpException, IOException {
if (logger.isInfoEnabled()) {
logger.info("发送至短信平台报文:" + msg);
}
RequestEntity entity = new ByteArrayRequestEntity(msg.getBytes("GBK"), "text/xml; charset=GBK");
HttpClient httpclient = new HttpClient();
int result;
PostMethod method = new PostMethod(SMS_SEND_URL);
method.setRequestEntity(entity);
method.setRequestHeader("Connection", "close");
//设定超时时间, 默认不限超时时间
httpclient.getHttpConnectionManager().getParams().setConnectionTimeout(30000);
result = httpclient.executeMethod(method);
if (logger.isInfoEnabled()) {
logger.info("短信平台通讯响应:" + result);
}
if (HttpStatus.SC_OK != result) {
logger.error("短信平台通讯响应:" + result);
logger.error("短信平台通讯响应报文:" + method.getResponseBodyAsString());
return false;
}
InputStream outStream = method.getResponseBodyAsStream();
SAXReader saxReader = new SAXReader();
try {
Document document = saxReader.read(outStream);
if (logger.isInfoEnabled()) {
logger.info("短信平台通讯响应报文:" + document.asXML());
}
Element root = document.getRootElement();
String[] values = new String[3];
Boolean found = false;
getResultCode(root, values, found);
String resultCode = "";
if (values != null) {
resultCode = values[1];
}
if ("0".equals(resultCode)) {
return true;
} else {
logger.error("短信平台通讯响应报文:" + resultCode);
return false;
}
} catch (DocumentException ex) {
ex.printStackTrace();
logger.error(ex.getMessage());
throw new RuntimeException(ex.getMessage());
}
}
private static void getResultCode(Element element, String[] results, Boolean found) {
if (!found) {
for (Iterator i = element.elementIterator(); i.hasNext() && !found; ) {//获得交易列表
Element node = (Element) i.next();
if ("Code" == node.getName()) {
results[0] = node.getName();
results[1] = node.getTextTrim();
found = true;
} else {
getResultCode(node, results, found);
}
}
}
}
/**
* 按顺序发送指定的短讯内容到指定手机号码中, 例如: 发送短讯(message) 到 手机(cellphone)
*
* @param cellphone
* @param message
* @return
*/
public static boolean sendMessage(String cellphone, String message) {
try {
if(StringUtils.isEmpty(cellphone)) {
return true;
}
boolean result = executeSend(buildMessage(cellphone, message));
//FIXME 关闭,发送失败自动重复, 最多重发三次
for (int i = 0; i < REPEAT_NUM && !result; i++) {
result = executeSend(buildMessage(cellphone, message));
}
return result;
} catch (HttpException e) {
logger.error(e.getMessage(), e);
throw new RuntimeException(e.getMessage());
} catch (IOException e) {
logger.error(e.getMessage(), e);
throw new RuntimeException(e.getMessage());
}
}
public static void main(String[] args) {
try {
//sendMessage("18953206865", "海尔短信平台测试短信");
sendMessage("13605329592", "海尔短信平台测试短信");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment