今天我想了一天如何实现网站用户在忘记了密码后,如何通过向手机发送验证码来重新设置密码。验证码的验证以及生成都已经做好了,现在主要是解决如何向用户手机发送短信。显然这需要一个第三方提供的短信接口,来帮助我们实现向用户手机发送验证码短信。这里我通过朋友介绍使用的是动力思维乐信这家的短信接口,(接入文档和代码示例地址:
http://www.lx598.com/document.html )接入起来比较简单,主要朋友告诉我,这家的短信响应速度快、到达率高、稳定,在这里也向大家推荐下,下面就拿我自己的网站,贴下实现代码:
这个是后端的实现代码:
package com.dlsw;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Random;
public class ShortMessage {
private accName = 电话号或者邮箱号;//用户账号
private accPwd = "e10adc3949ba59abbe56e057f20f883e";//登陆密码的 MD5 值 32 位
public String Send(String aimcodes, String content) throws UnsupportedEncodingException{
HttpURLConnection httpconn = null;
String content = content.trim();//发送短信内容
StringBuilder sb = new StringBuilder();
sb.append("http://www.lx198.com/sdk/send?accName="); //第三方接口地址及参数
sb.append(accName);
sb.append("&accPwd=").append(accPwd);
sb.append("&aimcodes=").append(aimcodes);
sb.append("&content=").append(URLEncoder.encode(content,"utf-8"));
String result = false;
System.out.println(sb.toString());
try {
URL url = new URL(sb.toString());
httpconn = (HttpURLConnection) url.openConnection();
BufferedReader read = new BufferedReader(new InputStreamReader( httpconn.getInputStream()));
result = read.readLine();
read.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally{
if( httpconn != null){
httpconn.disconnect();
httpconn = null;
}
}
return result;
}
public static void main(String[] args) {
String mobile="187xxxxxxxx";
String verifyCode = String.valueOf(new Random().nextInt(899999) + 100000);//随机生成验证码
String content="您正在使用密码找回功能,验证码为 " + verifyCode +" [动力思维] ";
try {
String result = new ShortMessage().Send(aimcodes, content);
System.out.println(result);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
}