系统实现短信功能,一般都引用官方的接口,在这里,我对自己做过的东西贴在这里,确实自己曾经学习过这些,也是对自己的学习做个备份。
首先该代码是在 spring 项目上开发的,需要 spring 相关包以及 log4j 相关包。
1、资源配置文件
#短信配置 sms.spCode=xxxxx sms.loginName=xxxxx sms.password=xxxxx sms.sendBasicUrl=xxxxx sms.searchBasicUrl=xxxxx
2、读取资源配置文件
package sms; import java.io.InputStream; import java.io.InputStreamReader; import java.net.URL; import java.util.Properties; public class ProConfig { private static Properties props = null; static { props = new Properties(); try { URL url = ProConfig.class.getClassLoader().getResource("sms.properties"); load(url.openStream()); } catch (Exception e) { System.out.println("读取配置信息出错:"+e.getMessage()); } } private static void load(InputStream inputStream) throws Exception { props.load(new InputStreamReader(inputStream, "UTF-8")); } public static String getProperty(String key) { return getProperty(key, ""); } public static String getProperty(String key, String defaultValue) { return props.getProperty(key, defaultValue); } }
3、短信构建对象
package sms; import java.util.ArrayList; import java.util.List; /** *短信构建对象
* * @author Selina * @qq 418114362 */ public class SmsBilder { /** * 手机号码(多个号码用”,”分隔),最多1000个号码 */ private String userNumber; /** * 短信内容, 最大700个字符 */ private String messageContent; /** * 接收者短信集合 */ private ListtoSmsList; /** * 获取一个短信构建对象 * @return */ public static SmsBilder getInstanBilder(){ return new SmsBilder(); } /** * 获取手机号码 * @return */ public String getUserNumber() { return userNumber; } /** * 设置手机号码 * @param messageContent */ public SmsBilder setUserNumner(String userNumber) { this.userNumber = userNumber; return this; } /** * 获取短信内容 * @return */ public String getMessageContent() { return messageContent; } /** * 设置短信内容 * @param messageContent */ public SmsBilder setMessageContent(String messageContent) { this.messageContent = messageContent; return this; } /** * 获取接收短信列表 * @return */ public List getSmsList() { return toSmsList; } /** * 添加接收短信 * @param email */ public SmsBilder addToSmsList(String sms) { if(this.toSmsList == null){ this.toSmsList = new ArrayList (); } this.toSmsList.add(sms); return this; } /** * 执行后台发送 */ public void sendInQueue(){ SmsQueue.addMailTask(this); } /** * 执行即刻发送 */ public String send(){ return SmsQueue.smsSend(this); } }
4、短信配置
package sms; import org.apache.commons.io.Charsets; /** *短信配置
* * @author Selina * @qq 418114362 */ public class SmsConfig { /** * 企业编号 */ public static String spCode ; /** * 用户名称 */ public static String loginName; /** * 用户密码 */ public static String password; /** * 字符集 */ public static String charset = Charsets.UTF_8.name(); /** * 超时时间 */ public static String timeout = "25000"; /** * 短信发送调用地址 */ public static String sendBasicUrl; /** * 短信剩余条数调用地址 */ public static String searchBasicUrl; static { spCode = ProConfig.getProperty("sms.spCode"); loginName = ProConfig.getProperty("sms.loginName"); password = ProConfig.getProperty("sms.password"); sendBasicUrl = ProConfig.getProperty("sms.sendBasicUrl"); searchBasicUrl = ProConfig.getProperty("sms.searchBasicUrl"); } }
5、短信工具类
package sms; import java.util.HashMap; import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** *短信工具类
* * @author Selina * @qq 418114362 */ public class SmsQueue extends AbstractQueue{ private static SmsQueue queue = new SmsQueue(); static { queue.start(); } private SmsQueue() { } /** * 添加短信任务 * @param smsBilder 短信构建对象 */ public static void addMailTask(SmsBilder smsBilder) { queue.addTask(smsBilder); } public void runTask(SmsBilder smsBilder) { SmsQueue.smsSend(smsBilder); } public static String smsSend(SmsBilder smsBilder){ String errorInfo = null; Throwable error = null; try{ //在这里执行短信发送 String url = SmsConfig.sendBasicUrl; Map params = new HashMap (); params.put("SpCode", SmsConfig.spCode); params.put("LoginName", SmsConfig.loginName); params.put("Password", SmsConfig.password); params.put("UserNumber", smsBilder.getUserNumber()); params.put("MessageContent", smsBilder.getMessageContent()); HttpRemote.doSomething(url, params); }catch(Exception e){ errorInfo = "短信发送错误"; error = e; }finally{ if(error!=null){ } } return errorInfo; } }
6、5点引用的两个工具类
package sms; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.BlockingQueue; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.DisposableBean; /** *抽象阻塞队列
* * @author Selina * @qq 418114362 */ public abstract class AbstractQueueimplements Runnable, DisposableBean { protected final Logger logger = LoggerFactory.getLogger(this.getClass()); protected BlockingQueue queue; private boolean started = false; public AbstractQueue() { this(30); } public AbstractQueue(int queueSize) { queue = new ArrayBlockingQueue (queueSize); } /** * 添加任务 * * @param task * @return */ public boolean addTask(E task) { return queue.offer(task); } public void destroy() throws Exception { int size = queue.size(); if (size == 0) { logger.info("queue size=0, exit."); return; } logger.info("queue still has size=" + size + ", wait 10s."); wait(10); logger.info("queue has size=" + queue.size() + ", still exit."); } /** * 获取队列当前长度 * * @return */ public int getQueueSize() { return queue.size(); } public void run() { this.started = true; while (true) { E task = null; try { task = queue.take(); runTask(task); } catch (Exception e) { logger.error("Exception occur while running task", e); } } } /** * 开始运行 */ public synchronized void start(){ if(started){ logger.warn("the queue has stsrted"); return ; } new Thread(this).start(); } /** * 是否在运行 * @return */ public boolean isStarted(){ return started; } /** * 任务执行方法(抽象方法) * * @param task */ protected abstract void runTask(E task); }
package sms; import java.util.ArrayList; import java.util.List; import java.util.Map; import org.apache.http.Header; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.NameValuePair; import org.apache.http.client.HttpClient; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.message.BasicNameValuePair; /** *公共类
* * @author Selina * @qq 418114362 */ public class HttpRemote { public static HttpClient doSomething(String url, Mapobject) throws Exception { HttpClient httpclient = new DefaultHttpClient(); try { HttpPost post = new HttpPost(url); List params = convertParam(object); post.setEntity(new UrlEncodedFormEntity(params, "UTF-8")); HttpResponse response = httpclient.execute(post); Header locationHeader = response.getFirstHeader("Location"); if (locationHeader == null) { return null; } int statusCode = response.getStatusLine().getStatusCode(); if (statusCode == HttpStatus.SC_MOVED_PERMANENTLY || statusCode == HttpStatus.SC_MOVED_TEMPORARILY || statusCode == HttpStatus.SC_SEE_OTHER || statusCode == HttpStatus.SC_TEMPORARY_REDIRECT) { String newUrl = response.getLastHeader("Location").getValue(); } } catch (Exception e) { } return httpclient; } private static List convertParam(Map params) { List list = new ArrayList (); if (params != null) { for (Map.Entry entry : params.entrySet()) { list.add(new BasicNameValuePair(entry.getKey(), entry .getValue())); } } return list; } }
综合以上代码,下面我们就来进行短信发送:
String userPhones = ""; userPhones="号码1,号码2"; SmsBilder smsBilder = new SmsBilder(); smsBilder.setUserNumner(userPhones); smsBilder.setMessageContent("Hello word!"); smsBilder.send();
这样就可以发送短信啦!
引用的短信服务接口为:http://ums.zj165.com/im/sp.jsp