httpclient-4.3.6.jar和httpcore-4.3.3.jar jar包
首先去网易云注册账号得到分配的app key 和 App Secret 开通短信有20条试用。使用的是httpclient post提交
请求信息分为 请求头和请求参数
请求头:必须5个参数,分别是:AppKey。Nonce。CurTime。CheckSum。Content-Type。 区分大小写
请求参数:mobile(手机号码),code(验证码),templateid(模板id),codeLen(验证码长度) 非必填的。
创建一个生成随机验证码的类:
import java.security.MessageDigest;
/**
* 验证码生成工具类
*/
public class CheckSumBuilder {
// 计算并获取CheckSum
public static String getCheckSum(String appSecret, String nonce, String curTime) {
return encode("sha1", appSecret + nonce + curTime);
}
// 计算并获取md5值
public static String getMD5(String requestBody) {
return encode("md5", requestBody);
}
private static String encode(String algorithm, String value) {
if (value == null) {
return null;
}
try {
MessageDigest messageDigest = MessageDigest.getInstance(algorithm);
messageDigest.update(value.getBytes());
return getFormattedText(messageDigest.digest());
} catch (Exception e) {
throw new RuntimeException(e);
}
}
private static String getFormattedText(byte[] bytes) {
int len = bytes.length;
StringBuilder buf = new StringBuilder(len * 2);
for (int j = 0; j < len; j++) {
buf.append(HEX_DIGITS[(bytes[j] >> 4) & 0x0f]);
buf.append(HEX_DIGITS[bytes[j] & 0x0f]);
}
return buf.toString();
}
private static final char[] HEX_DIGITS =
{'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
}
根据api提供的java代码创建一个测试类
import com.alibaba.fastjson.JSON;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
/**
*发送请求到网易云
*success:网易云成功发送验证码到手机
*/
public class SendCode {
public static void main(String[] args) throws Exception {
System.out.println(sendMsg("******************"));
}
private static final String SERVER_URL = "https://api.netease.im/sms/sendcode.action";//发送验证码的请求路径URL
private static final String APP_KEY = "***************************************";//网易云信分配的账号
private static final String APP_SECRET = "*********";//网易云信分配的密钥
private static final String NONCE = "123456";//随机数
//短信模板ID
private static final String TEMPLATEID="3094150";
//验证码长度,范围4~10,默认为4
private static final String CODELEN="6";
/**
*
* @param phone 手机号
* @return
* @throws IOException
*/
public static MessageVo sendMsg(String phone) throws IOException {
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpPost post = new HttpPost(SERVER_URL);
String curTime = String.valueOf((new Date().getTime() / 1000L));
/*通过验证码工具类生成随机数*/
String checkSum = CheckSumBuilder.getCheckSum(APP_SECRET, NONCE, curTime);
System.out.println("验证码:"+checkSum);
//设置请求的header 请求头
post.addHeader("AppKey", APP_KEY);
post.addHeader("Nonce", NONCE);
post.addHeader("CurTime", curTime);
post.addHeader("CheckSum", checkSum);
post.addHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
//设置请求参数
List
/*启用短信模板*/
nameValuePairs.add(new BasicNameValuePair("templateid", TEMPLATEID));
/*手机号*/
nameValuePairs.add(new BasicNameValuePair("mobile",phone));
/*验证码长度*/
nameValuePairs.add(new BasicNameValuePair("codeLen",CODELEN));
/*将请求头信息和请求参数放入一个entity里面*/
post.setEntity(new UrlEncodedFormEntity(nameValuePairs,"utf-8"));
//执行请求
HttpResponse response = httpclient.execute(post);
/*获取返回的信息 是一个json字符串*/
String responseEntity = EntityUtils.toString(response.getEntity(),"utf-8");
MessageVo messageVo=new MessageVo();
//判断是否发送成功,发送成功返回true 获取返回的状态码
String code = JSON.parseObject(responseEntity).getString("code")
System.out.println("状态吗:"+code);
messageVo.setCode(code);
messageVo.setObj(obj);
return messageVo;
// if (code.equals("200")) {
// return "success";
// }
// return "error";
}
}
然后就是一个输入手机号码和验证码的校验类
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import com.alibaba.fastjson.JSON;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
/**
* 校验验证码输入是否正确
*/
public class MobileMessageCheck {
public static void main(String[] args) throws Exception {
System.out.println(checkMsg("187********","626712"));
}
private static final String SERVER_URL = "https://api.netease.im/sms/verifycode.action";//校验验证码的请求路径URL
private static final String APP_KEY = "*********************************";//网易云信分配的账号
private static final String APP_SECRET = "***************";//网易云信分配的密钥
private static final String NONCE = "123456";//随机数
/**
*
* @param phone 手机号
* @param sum 验证码
* @return
* @throws IOException
*/
public static MessageVo checkMsg(String phone, String sum) throws IOException {
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpPost post = new HttpPost(SERVER_URL);
String curTime = String.valueOf((new Date().getTime() / 1000L));
String checkSum = CheckSumBuilder.getCheckSum(APP_SECRET, NONCE, curTime);
//设置请求的header
post.addHeader("AppKey", APP_KEY);
post.addHeader("Nonce", NONCE);
post.addHeader("CurTime", curTime);
post.addHeader("CheckSum", checkSum);
post.addHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
//设置请求参数
List
nameValuePairs.add(new BasicNameValuePair("mobile", phone));
nameValuePairs.add(new BasicNameValuePair("code", sum));
post.setEntity(new UrlEncodedFormEntity(nameValuePairs, "utf-8"));
//执行请求
HttpResponse response = httpclient.execute(post);
String responseEntity = EntityUtils.toString(response.getEntity(), "utf-8");
MessageVo messageVo=new MessageVo();
//判断是否发送成功,发送成功返回true
String code = JSON.parseObject(responseEntity).getString("code");
System.out.println("状态吗:"+code);
messageVo.setCode(code);
return messageVo;
// if (code.equals("200")) {
// return "success";
// }
// return "error";
}
}
创建实体类MessageVo用来存储状态码与验证码属性
创建UsreServlet类,与jsp互动。通过ajax传值,判断
前台Ajax代码