import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.URL; import java.net.URLConnection; import java.text.SimpleDateFormat; import java.util.Date; public class SMSUtils { private static String corpid = "xxx";// 用戶 private static String pswd = "xxx";// 密碼 private static String loginParam = "?corpid=" + corpid + "&pswd=" + pswd; private static int timeOut = 20000;//超時 /** * 發送單條短信 */ public static String sendGet(String phone, String msg) { SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmsss"); String timeStr = sdf.format(new Date());// 當前的時間戳 BufferedReader in = null; StringBuilder http = new StringBuilder(); http.append("http://120.31.132.210/httpinterface/mt.php"); http.append(loginParam); http.append("&smsid="); http.append(phone); http.append(timeStr); http.append("&mob="); http.append(phone); http.append("&msg="); http.append(msg); String codeStr = "";// 存放返回值的代碼 try { URL realUrl = new URL(http.toString()); // 打開和URL之間的鏈接 URLConnection connection = realUrl.openConnection(); // 設置通用的請求屬性 connection.setRequestProperty("accept", "*/*"); connection.setRequestProperty("connection", "Keep-Alive"); connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)"); connection.setReadTimeout(timeOut); // 創建實際的鏈接 connection.connect(); // 定義 BufferedReader輸入流來讀取URL的響應 in = new BufferedReader(new InputStreamReader(connection.getInputStream())); String line; while ((line = in.readLine()) != null) { codeStr += line; } } catch (IOException io) { System.out.println("發送GET請求出現異常!" + io); io.printStackTrace(); } // 使用finally塊來關閉輸入流 finally { try { if (in != null) { in.close(); } } catch (Exception e2) { e2.printStackTrace(); } } return codeStr; } public static void main(String[] args) { String mob = "電話號碼"; String msg = "短信內容";// 短信的內容 System.out.println("短信號碼:" + mob); String response = sendGet(mob, msg); System.out.println("返回的驗證碼:" + response); } }