码迷,mamicode.com
首页 > 移动开发 > 详细

第一次发博,发个简单的Java程序发送手机短信验证

时间:2017-07-08 18:42:53      阅读:350      评论:0      收藏:0      [点我收藏+]

标签:java   void   java.net   关闭   测试   list   用户   encode   ror   

最近在准备一个项目,想的登录时候用手机验证,就通过上网查阅了一下手机验证的实现方法,原来超级简单,下面将一步一步介绍。

1.去中国网建注册一个账号密码,首次注册送五条免费短信和3条免费彩信。具体的网址是

       http://www.smschinese.cn/api.shtml

2.注册完成之后进去查看给你的短信秘钥

 

            技术分享

3.有了这个秘钥就超级简单了,导入jar包,下面的代码第一个基本不用该,直接粘贴,第二个改成自己的信息就可以了

  1 package duanxinyanzheng;
  2 
  3   
  4 import java.io.IOException;
  5 import java.net.URL;
  6 import java.util.ArrayList;
  7 import java.util.HashMap;
  8 import java.util.List;
  9 import java.util.Map;
 10 
 11 import org.apache.http.HttpEntity;
 12 import org.apache.http.NameValuePair;
 13 import org.apache.http.client.config.RequestConfig;
 14 import org.apache.http.client.entity.UrlEncodedFormEntity;
 15 import org.apache.http.client.methods.CloseableHttpResponse;
 16 import org.apache.http.client.methods.HttpGet;
 17 import org.apache.http.client.methods.HttpPost;
 18 import org.apache.http.conn.ssl.DefaultHostnameVerifier;
 19 import org.apache.http.conn.util.PublicSuffixMatcher;
 20 import org.apache.http.conn.util.PublicSuffixMatcherLoader;
 21 import org.apache.http.impl.client.CloseableHttpClient;
 22 import org.apache.http.impl.client.HttpClients;
 23 import org.apache.http.message.BasicNameValuePair;
 24 import org.apache.http.util.EntityUtils;
 25   
 26   
 27 public class HttpClientUtil {  
 28     private RequestConfig requestConfig = RequestConfig.custom()  
 29             .setSocketTimeout(15000)  
 30             .setConnectTimeout(15000)  
 31             .setConnectionRequestTimeout(15000)  
 32             .build();  
 33       
 34     private static HttpClientUtil instance = null;  
 35     private HttpClientUtil(){}  
 36     public static HttpClientUtil getInstance(){  
 37         if (instance == null) {  
 38             instance = new HttpClientUtil();  
 39         }  
 40         return instance;  
 41     }  
 42       
 43     /** 
 44      * 发送 post请求 
 45      * @param httpUrl 地址 
 46      */  
 47     public String sendHttpPost(String httpUrl) {  
 48         HttpPost httpPost = new HttpPost(httpUrl);// 创建httpPost    
 49         return sendHttpPost(httpPost,"utf-8");  
 50     }  
 51       
 52       
 53     /** 
 54      * 发送 post请求 
 55      * @param httpUrl 地址 
 56      * @param maps 参数 
 57      *  @param type 字符编码格式 
 58      */  
 59     public String sendHttpPost(String httpUrl, Map<String, String> maps,String type) {  
 60         HttpPost httpPost = new HttpPost(httpUrl);// 创建httpPost    
 61         // 创建参数队列    
 62         List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();  
 63         for (String key : maps.keySet()) {  
 64             nameValuePairs.add(new BasicNameValuePair(key, maps.get(key)));  
 65         }  
 66         try {  
 67             httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs, type));  
 68         } catch (Exception e) {  
 69             e.printStackTrace();  
 70         }  
 71         return sendHttpPost(httpPost,type);  
 72     }  
 73       
 74     /** 
 75      * 发送Post请求 
 76      * @param httpPost 
 77      * @return 
 78      */  
 79     private String sendHttpPost(HttpPost httpPost,String reponseType) {  
 80         CloseableHttpClient httpClient = null;  
 81         CloseableHttpResponse response = null;  
 82         HttpEntity entity = null;  
 83         String responseContent = null;  
 84         try {  
 85             // 创建默认的httpClient实例.  
 86             httpClient = HttpClients.createDefault();  
 87             httpPost.setConfig(requestConfig);  
 88             // 执行请求  
 89             response = httpClient.execute(httpPost);  
 90             entity = response.getEntity();  
 91             responseContent = EntityUtils.toString(entity, reponseType);  
 92         } catch (Exception e) {  
 93             e.printStackTrace();  
 94         } finally {  
 95             try {  
 96                 // 关闭连接,释放资源  
 97                 if (response != null) {  
 98                     response.close();  
 99                 }  
100                 if (httpClient != null) {  
101                     httpClient.close();  
102                 }  
103             } catch (IOException e) {  
104                 e.printStackTrace();  
105             }  
106         }  
107         return responseContent;  
108     }  
109   
110     /** 
111      * 发送 get请求 
112      * @param httpUrl 
113      */  
114     public String sendHttpGet(String httpUrl) {  
115         HttpGet httpGet = new HttpGet(httpUrl);// 创建get请求  
116         return sendHttpGet(httpGet);  
117     }  
118       
119     /** 
120      * 发送 get请求Https 
121      * @param httpUrl 
122      */  
123     public String sendHttpsGet(String httpUrl) {  
124         HttpGet httpGet = new HttpGet(httpUrl);// 创建get请求  
125         return sendHttpsGet(httpGet);  
126     }  
127     
128     /**
129      * @Title: sendMsgUtf8
130      * @Description: TODO(发送utf8)
131      * @param: @param Uid
132      * @param: @param Key
133      * @param: @param content
134      * @param: @param mobiles
135      * @param: @return      
136      * @date: 2017-3-22 下午5:58:07
137      * @throws
138      */
139     @SuppressWarnings({ "rawtypes", "unchecked" })
140     public int sendMsgUtf8(String Uid,String Key,String content,String mobiles){
141         Map maps = new HashMap();
142         maps.put("Uid", Uid);
143         maps.put("Key", Key);
144         maps.put("smsMob", mobiles);
145         maps.put("smsText", content);
146         String result = sendHttpPost("http://utf8.sms.webchinese.cn", maps, "utf-8");
147         return Integer.parseInt(result);
148     }
149     
150     /**
151      * @Title: sendMsgUtf8
152      * @Description: TODO(发送utf8)
153      * @param: @param Uid
154      * @param: @param Key
155      * @param: @param content
156      * @param: @param mobiles
157      * @param: @return     
158      * @return: int     
159      * @author:  ly
160      * @date: 2017-3-22 下午5:58:07
161      * @throws
162      */
163     @SuppressWarnings({ "rawtypes", "unchecked" })
164     public int sendMsgGbk(String Uid,String Key,String content,String mobiles){
165         Map maps = new HashMap();
166         maps.put("Uid", Uid);
167         maps.put("Key", Key);
168         maps.put("smsMob", mobiles);
169         maps.put("smsText", content);
170         String result = sendHttpPost("http://gbk.sms.webchinese.cn", maps, "gbk");
171         return Integer.parseInt(result);
172     }
173       
174     /** 
175      * 发送Get请求 
176      * @param httpPost 
177      * @return 
178      */  
179     private String sendHttpGet(HttpGet httpGet) {  
180         CloseableHttpClient httpClient = null;  
181         CloseableHttpResponse response = null;  
182         HttpEntity entity = null;  
183         String responseContent = null;  
184         try {  
185             // 创建默认的httpClient实例.  
186             httpClient = HttpClients.createDefault();  
187             httpGet.setConfig(requestConfig);  
188             // 执行请求  
189             response = httpClient.execute(httpGet);  
190             entity = response.getEntity();  
191             responseContent = EntityUtils.toString(entity, "UTF-8");  
192         } catch (Exception e) {  
193             e.printStackTrace();  
194         } finally {  
195             try {  
196                 // 关闭连接,释放资源  
197                 if (response != null) {  
198                     response.close();  
199                 }  
200                 if (httpClient != null) {  
201                     httpClient.close();  
202                 }  
203             } catch (IOException e) {  
204                 e.printStackTrace();  
205             }  
206         }  
207         return responseContent;  
208     }  
209       
210     /** 
211      * 发送Get请求Https 
212      * @param httpPost 
213      * @return 
214      */  
215     private String sendHttpsGet(HttpGet httpGet) {  
216         CloseableHttpClient httpClient = null;  
217         CloseableHttpResponse response = null;  
218         HttpEntity entity = null;  
219         String responseContent = null;  
220         try {  
221             // 创建默认的httpClient实例.  
222             PublicSuffixMatcher publicSuffixMatcher = PublicSuffixMatcherLoader.load(new URL(httpGet.getURI().toString()));  
223             DefaultHostnameVerifier hostnameVerifier = new DefaultHostnameVerifier(publicSuffixMatcher);  
224             httpClient = HttpClients.custom().setSSLHostnameVerifier(hostnameVerifier).build();  
225             httpGet.setConfig(requestConfig);  
226             // 执行请求  
227             response = httpClient.execute(httpGet);  
228             entity = response.getEntity();  
229             responseContent = EntityUtils.toString(entity, "UTF-8");  
230         } catch (Exception e) {  
231             e.printStackTrace();  
232         } finally {  
233             try {  
234                 // 关闭连接,释放资源  
235                 if (response != null) {  
236                     response.close();  
237                 }  
238                 if (httpClient != null) {  
239                     httpClient.close();  
240                 }  
241             } catch (IOException e) {  
242                 e.printStackTrace();  
243             }  
244         }  
245         return responseContent;  
246     }  
247     
248     /**
249      * @Title: getErrorMsg
250      * @Description: TODO(返回异常原因)
251      * @param: @param errorCode
252      */
253     public String getErrorMsg(int errorCode){
254         if(errorCode==-1){
255             return "没有该用户账户";
256         }else if(errorCode==-2){
257             return "接口密钥不正确";
258         }else if(errorCode==-3){
259             return "短信数量不足";
260         }else if(errorCode==-4){
261             return "手机号格式不正确";
262         }else if(errorCode==-21){
263             return "MD5接口密钥加密不正确";
264         }else if(errorCode==-11){
265             return "该用户被禁用";
266         }else if(errorCode==-14){
267             return "短信内容出现非法字符";
268         }else if(errorCode==-41){
269             return "手机号码为空";
270         }else if(errorCode==-42){
271             return "短信内容为空";
272         }else if(errorCode==-51){
273             return "短信签名格式不正确";
274         }else if(errorCode==-6){
275             return "IP限制";
276         }else{
277             return "未知错误码:"+errorCode;
278         }
279     }
280 }  

这就是测试代码,里面的内容改成你自己的。

 1 package duanxinyanzheng;
 2 
 3 import java.util.HashMap;
 4 import java.util.Map;
 5 
 6 /**  
 7  * @Title: http://www.smschinese.cn/api.shtml
 8  * @date 2011-3-22
 9  * @version V1.2  
10  */
11 public class test {
12     
13     //用户名
14     private static String Uid = "你自己的";
15     
16     //接口安全秘钥
17     private static String Key = "你的秘钥(不是登录密码)";
18     
19     //手机号码,多个号码如13800000000,13800000001,13800000002
20     private static String smsMob = "18434391711";
21     
22     //短信内容
23     private static String smsText = "这是自己的测试!【这是验证格式的必须填】";
24     
25     
26     public static void main(String[] args) {
27         
28         HttpClientUtil client = HttpClientUtil.getInstance();
29         
30         //UTF发送
31         int result = client.sendMsgUtf8(Uid, Key, smsText, smsMob);
32         if(result>0){
33             System.out.println("UTF8成功发送条数=="+result);
34         }else{
35             System.out.println(client.getErrorMsg(result));
36         }
37     }
38 }

 

 

上述就可以运行了,是不是超级简单,以前觉得好深奥。上面需要注意 秘钥不是登录密码,内容后面要加上【公司名称】,便于接口进行校验。

三个需要的Jar包可以在上面的网址中下载。

第一次发博,发个简单的Java程序发送手机短信验证

标签:java   void   java.net   关闭   测试   list   用户   encode   ror   

原文地址:http://www.cnblogs.com/qlqwjy/p/7137510.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!