SMSUtil
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;public class SMSUtils {/*** 調用postNormalMessage方法* 需要5個參數* 參數1:ID(是什么ID)* 參數2:密碼* 參數3:手機號(這里的參數是一個字符串,但是如果是多個是用逗號隔開?還是只能傳一個,如果是多個需要循環遍歷)* 參數5:Type A/LA代表選擇哪種類型 決定長度 收費不一樣 默認是A LA收費更貴* 參數4:message 代表消息主體*/public static void postNormalMessage(String message,String mobile) {/*** 供應商的地址*/final String gatewayURL ="https://www.commzgate.net/gateway/SendMsg";/*** 這個ID是供應商提供的,不是郵箱ID*/final String ID = "admin";/*** 密碼*/final String password = "1234";/*** 需要發送的手機號碼,到時候可能需要通過傳入參數的形式發送*///final String mobile = "18888888888";/*** 參數5:Type A/LA代表選擇哪種類型 決定長度 收費不一樣 默認是A LA收費更貴*/final String type = "A";/*** 定義一個長度為2的String數組 Array with 2 parts.* Part 1 is what YOU receive from CG.* Part 2 is what YOU send*/String[] response = new String[2];try{ HttpURLConnection httpURLConnector = null;//聲明數據輸出流對象DataOutputStream out =null;BufferedReader in =null;//1.得到訪問地址的URLURL theURL = new URL(gatewayURL+"?");//2.得到網絡訪問對象java.net.HttpURLConnectionhttpURLConnector = (HttpURLConnection) theURL.openConnection();//3.設置請求方式為POSThttpURLConnector.setRequestMethod("POST");httpURLConnector.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");//4.設置請求參數(過期時間,輸入、輸出流、訪問方式),以流的形式進行連接 //設置是否從httpUrlConnection讀入httpURLConnector.setDoInput(true);//設置是否向HttpURLConnection輸出httpURLConnector.setDoOutput(true);//設置超時時間httpURLConnector.setReadTimeout(30000);//30000//連接httpURLConnector.connect();//httpURLConnector.getOutputStream()獲取outputStream//實例化數據輸出流對象 從流中讀取響應信息out = new DataOutputStream(httpURLConnector.getOutputStream());StringBuffer sb = new StringBuffer();sb.append("ID=").append(URLEncoder.encode(ID, "UTF-8"));sb.append("&").append("Password=").append(URLEncoder.encode(password, "UTF-8"));sb.append("&").append("Mobile=").append(URLEncoder.encode(mobile, "UTF-8"));sb.append("&").append("Message=").append(URLEncoder.encode(message, "UTF-8"));sb.append("&").append("Type=").append(URLEncoder.encode(type, "UTF-8"));//這里發送的信息是自己給的參數拼裝好的response[1] = "Posting: "+gatewayURL+"?"+sb.toString();//把消息體寫給CG,writeBytes()傳的參數是字符串out.writeBytes(sb.toString());//API提供的是傳入字符串,所以傳入字節數組先放在這里//out.write(sb.toString().getBytes());out.close();//這個判斷是自己加的,默認給的api是沒有這個判斷的if(httpURLConnector.getResponseCode()==200) {//正常成功是200的,只是不知道提供API會不會做特殊處理System.out.println("如果responseCode等于200就說明請求成功了");}else {System.out.println("請求失敗");}in = new BufferedReader(new InputStreamReader(httpURLConnector.getInputStream()));//讀取數據,這里只讀取一行,所以CG只返回一行,不需要循環讀取response[0] = in.readLine();// 關閉流in.close();// 斷開連接,釋放資源httpURLConnector.disconnect();}catch(Exception e){System.out.println("發送短信有異常");}}}
?
總結
- 上一篇: Disruptor并发框架-2
- 下一篇: SocketIO-nio