1. 程式人生 > >第一次發博,發個簡單的Java程序發送手機短信驗證

第一次發博,發個簡單的Java程序發送手機短信驗證

map() dht itl air created 導入 error cor images

最近在準備一個項目,想的登錄時候用手機驗證,就通過上網查閱了一下手機驗證的實現方法,原來超級簡單,下面將一步一步介紹。

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程序發送手機短信驗證