短信工具类

  有一个好的工具,会让你的开发事半功倍。就我目前的几个项目里,都有用到短信模块。我先给大家介绍一款第三方的短信接口(这是接口文档下载地址:http://download.csdn.net/detail/privacy_googol/9672862)。

  结合文档和以下封装的工具类(调用短信平台提供的接口,遵循短信平台的接口规范即可),让你迅速掌握短信发送技能。

 1 import java.io.BufferedReader;
 2 import java.io.IOException;
 3 import java.io.InputStreamReader;
 4 import java.net.HttpURLConnection;
 5 import java.net.URL;
 6 import java.net.URLEncoder;
 7 
 8 //支持SHA-1/MD5消息摘要的工具类.
 9 import com.common.security.Digests;
10 
11 /*
12 功能:        企信通 HTTP接口 发送短信
13 说明:        http://api.cnsms.cn/?ac=send&uid=用户账号&pwd=MD5位32密码&mobile=号码&content=内容
14 状态:
15     100 发送成功
16     101 验证失败
17     102 短信不足
18     103 操作失败
19     104 非法字符
20     105 内容过多
21     106 号码过多
22     107 频率过快
23     108 号码内容空
24     109 账号冻结
25     110 禁止频繁单条发送
26     111 系统暂定发送
27     112 号码不正确
28     120 系统升级
29 */
30 public class SMSUtils {
31 
32 
33     //发送短信,uid,pwd,参数值请向企信通申请, tel:发送的手机号, content:发送的内容
34     public static String send(String uid, String pwd, String tel, String content) throws IOException {
35         
36         // 创建StringBuffer对象用来操作字符串
37         StringBuffer sb = new StringBuffer("http://api.cnsms.cn/?");
38 
39         // 向StringBuffer追加用户名
40         sb.append("ac=send&uid="+uid);//在此申请企信通uid,并进行配置用户名
41         
42         // 向StringBuffer追加密码(密码采用MD5 32位 小写)
43         sb.append("&encode=utf8");
44 
45         // 向StringBuffer追加密码(密码采用MD5 32位 小写)
46         sb.append("&pwd="+Digests.string2MD5(pwd));//在此申请企信通uid,并进行配置密码
47 
48         // 向StringBuffer追加手机号码
49         sb.append("&mobile="+tel);
50         // 向StringBuffer追加消息内容转URL标准码
51         sb.append("&content="+URLEncoder.encode(content,"utf8"));
52 
53         // 创建url对象
54         URL url = new URL(sb.toString());
55 
56         // 打开url连接
57         HttpURLConnection connection = (HttpURLConnection) url.openConnection();
58 
59         // 设置url请求方式 ‘get’ 或者 ‘post’
60         connection.setRequestMethod("POST");
61 
62         // 发送
63         BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
64 
65         // 返回发送结果
66         String inputline = in.readLine();
67         return inputline;
68 
69     }
70 
71 
72 
73 }

 

  1 import java.io.IOException;
  2 import java.io.InputStream;
  3 import java.security.GeneralSecurityException;
  4 import java.security.MessageDigest;
  5 import java.security.SecureRandom;
  6 
  7 import org.apache.commons.lang3.Validate;
  8 
  9 //关于异常的工具类
 10 import com.common.utils.Exceptions;
 11 
 12 /**
 13  * 支持SHA-1/MD5消息摘要的工具类.
 14  * 
 15  * 返回ByteSource,可进一步被编码为Hex, Base64或UrlSafeBase64
 16  * 
 17  */
 18 public class Digests {
 19 
 20     private static final String SHA1 = "SHA-1";
 21     private static final String MD5 = "MD5";
 22 
 23     private static SecureRandom random = new SecureRandom();
 24 
 25     /**
 26      * 对输入字符串进行md5散列.
 27      */
 28     public static byte[] md5(byte[] input) {
 29         return digest(input, MD5, null, 1);
 30     }
 31     public static byte[] md5(byte[] input, int iterations) {
 32         return digest(input, MD5, null, iterations);
 33     }
 34     
 35     /**
 36      * 对输入字符串进行sha1散列.
 37      */
 38     public static byte[] sha1(byte[] input) {
 39         return digest(input, SHA1, null, 1);
 40     }
 41 
 42     public static byte[] sha1(byte[] input, byte[] salt) {
 43         return digest(input, SHA1, salt, 1);
 44     }
 45 
 46     public static byte[] sha1(byte[] input, byte[] salt, int iterations) {
 47         return digest(input, SHA1, salt, iterations);
 48     }
 49 
 50     /**
 51      * 对字符串进行散列, 支持md5与sha1算法.
 52      */
 53     private static byte[] digest(byte[] input, String algorithm, byte[] salt, int iterations) {
 54         try {
 55             MessageDigest digest = MessageDigest.getInstance(algorithm);
 56 
 57             if (salt != null) {
 58                 digest.update(salt);
 59             }
 60 
 61             byte[] result = digest.digest(input);
 62 
 63             for (int i = 1; i < iterations; i++) {
 64                 digest.reset();
 65                 result = digest.digest(result);
 66             }
 67             return result;
 68         } catch (GeneralSecurityException e) {
 69             throw Exceptions.unchecked(e);
 70         }
 71     }
 72 
 73     /**
 74      * 生成随机的Byte[]作为salt.
 75      * 
 76      * @param numBytes byte数组的大小
 77      */
 78     public static byte[] generateSalt(int numBytes) {
 79         Validate.isTrue(numBytes > 0, "numBytes argument must be a positive integer (1 or larger)", numBytes);
 80 
 81         byte[] bytes = new byte[numBytes];
 82         random.nextBytes(bytes);
 83         return bytes;
 84     }
 85 
 86     /**
 87      * 对文件进行md5散列.
 88      */
 89     public static byte[] md5(InputStream input) throws IOException {
 90         return digest(input, MD5);
 91     }
 92 
 93     /**
 94      * 对文件进行sha1散列.
 95      */
 96     public static byte[] sha1(InputStream input) throws IOException {
 97         return digest(input, SHA1);
 98     }
 99 
100     private static byte[] digest(InputStream input, String algorithm) throws IOException {
101         try {
102             MessageDigest messageDigest = MessageDigest.getInstance(algorithm);
103             int bufferLength = 8 * 1024;
104             byte[] buffer = new byte[bufferLength];
105             int read = input.read(buffer, 0, bufferLength);
106 
107             while (read > -1) {
108                 messageDigest.update(buffer, 0, read);
109                 read = input.read(buffer, 0, bufferLength);
110             }
111 
112             return messageDigest.digest();
113         } catch (GeneralSecurityException e) {
114             throw Exceptions.unchecked(e);
115         }
116     }
117     
118     public static String string2MD5(String inStr){  
119         MessageDigest md5 = null;  
120         try{  
121             md5 = MessageDigest.getInstance("MD5");  
122         }catch (Exception e){  
123             System.out.println(e.toString());  
124             e.printStackTrace();  
125             return "";  
126         }  
127         char[] charArray = inStr.toCharArray();  
128         byte[] byteArray = new byte[charArray.length];  
129   
130         for (int i = 0; i < charArray.length; i++)  
131             byteArray[i] = (byte) charArray[i];  
132         byte[] md5Bytes = md5.digest(byteArray);  
133         StringBuffer hexValue = new StringBuffer();  
134         for (int i = 0; i < md5Bytes.length; i++){  
135             int val = ((int) md5Bytes[i]) & 0xff;  
136             if (val < 16)  
137                 hexValue.append("0");  
138             hexValue.append(Integer.toHexString(val));  
139         }  
140         return hexValue.toString();  
141   
142     }  
143 }

 

 1 import java.io.PrintWriter;
 2 import java.io.StringWriter;
 3 
 4 import javax.servlet.http.HttpServletRequest;
 5 
 6 /**
 7  * 关于异常的工具类.
 8  *
 9  */
10 public class Exceptions {
11 
12     /**
13      * 将CheckedException转换为UncheckedException.
14      */
15     public static RuntimeException unchecked(Exception e) {
16         if (e instanceof RuntimeException) {
17             return (RuntimeException) e;
18         } else {
19             return new RuntimeException(e);
20         }
21     }
22 
23     /**
24      * 将ErrorStack转化为String.
25      */
26     public static String getStackTraceAsString(Throwable e) {
27         if (e == null){
28             return "";
29         }
30         StringWriter stringWriter = new StringWriter();
31         e.printStackTrace(new PrintWriter(stringWriter));
32         return stringWriter.toString();
33     }
34 
35     /**
36      * 判断异常是否由某些底层的异常引起.
37      */
38     public static boolean isCausedBy(Exception ex, Class<? extends Exception>... causeExceptionClasses) {
39         Throwable cause = ex.getCause();
40         while (cause != null) {
41             for (Class<? extends Exception> causeClass : causeExceptionClasses) {
42                 if (causeClass.isInstance(cause)) {
43                     return true;
44                 }
45             }
46             cause = cause.getCause();
47         }
48         return false;
49     }
50 
51     /**
52      * 在request中获取异常类
53      * @param request
54      * @return 
55      */
56     public static Throwable getThrowable(HttpServletRequest request){
57         Throwable ex = null;
58         if (request.getAttribute("exception") != null) {
59             ex = (Throwable) request.getAttribute("exception");
60         } else if (request.getAttribute("javax.servlet.error.exception") != null) {
61             ex = (Throwable) request.getAttribute("javax.servlet.error.exception");
62         }
63         return ex;
64     }
65     
66 }

 

转载请注明出处!

http://www.cnblogs.com/libingbin/

感谢您的阅读。如果文章对您有用,那么请轻轻点个赞,以资鼓励。

posted on 2016-10-07 13:06  bingbinlee  阅读(1147)  评论(0编辑  收藏  举报