使用短信接口发送消息是非常简单的一些操作,找到短信经销商后,他们会给我们提供一些短信提交接口说明文档和短信提交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("短信发送失败了");
}