使用短信接口發送消息是非常簡單的一些操作,找到短信經銷商後,他們會給我們提供一些短信提交接口說明文檔和短信提交DEMO,首先不要着急查看短信提交DEMO,先查看短信接口文檔,他們會有一個短信接口地址,以及短信調取的方法,方法中包含需要傳遞的參數。看明白後,再查看DEMO這樣就簡單多了。
下面是我在項目中發送短信驗證碼的例子,僅供參考:
如何生成驗證碼參考:http://blog.csdn.net/smilejuan/article/details/52251103文章
首先有一個發送短信的封裝方法:
/**
* 發送短息接口
* @param postData 發送短信的參數
* @param postUrl 發送路徑及調用方法
* @return
*/
public static String SMS(String postData, String postUrl) {
try {
//發送POST請求
URL url = new URL(postUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setUseCaches(false);
conn.setDoOutput(true);
conn.setRequestProperty("Content-Length", "" + postData.length());
OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
out.write(postData);
out.flush();
out.close();
//獲取響應狀態
if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) {
System.out.println("connect failed!");
return "";
}
//獲取響應內容體
String line, result = "";
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));
while ((line = in.readLine()) != null) {
result += line + "\n";
}
in.close();
return result;
} catch (IOException e) {
e.printStackTrace(System.out);
}
return "";
}
封裝好該方法後,在controller調用,並解析接口返回信息,判斷短信是否發送成功
//發送短信
String PostData = "sname=DL-wangan12&spwd=wangan12&scorpid=&sprdid=1012818&sdst="+telephone+"&smsg="+java.net.URLEncoder.encode("您的驗證碼是:"+code+"【xxx】","utf-8");
String ret =this.SMS(PostData, "http://cf.lmobile.cn/submitdata/Service.asmx/g_Submit");
Document doc = null;
doc = DocumentHelper.parseText(ret); // 將字符串轉爲XML
Element rootElt = doc.getRootElement(); // 獲取根節點
//獲取根節點下的子節點
Element eName = rootElt.element("State");
//節點內容
String name=eName.getTextTrim();
if(name.equals("0")){
System.out.println("短信發送成功了");
}else{
System.out.println("短信發送失敗了");
}