java发送网易云短信验证码(语音和短信)

java发送网易云短信验证码(语音和短信)

1,先拷贝架包

commons-codec
commons-codec
1.10


org.apache.httpcomponents
httpclient
4.5.2


org.apache.commons
commons-lang3
3.4


com.alibaba
fastjson
1.2.7


javax.servlet
servlet-api
2.5
provided

2,创建生成验证码的类
package com.baizhi.util.wyy;

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’};
    }
    3,网易发送验证码工具类

package com.baizhi.util.wyy;

import com.alibaba.fastjson.JSON;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**

  • 网易发送验证码
  • @author Pengyl

*/
public class SendCode1 {
//发送验证码的请求路径URL
//1,通知类短信,请求的URL(https://api.netease.im/sms/sendtemplate.action )
//2,运营类短信,请求的URL(https://api.netease.im/sms/sendtemplate.action )
//3,验证码短信,请求的URL(https://api.netease.im/sms/sendcode.action )
private static final String
SERVER_URL=“https://api.netease.im/sms/sendcode.action”;
//网易云信分配的账号,请替换你在管理后台应用下申请的Appkey
private static final String
APP_KEY=“2bc0a2711b62fa8adb1c412166b64c1a”;
//网易云信分配的密钥,请替换你在管理后台应用下申请的appSecret
private static final String APP_SECRET=“84f57b6f3195”;
//随机数
private static final String NONCE=“123456”;
//短信模板ID
//这个地方默认的是语音验证码,可以创建短信模板,大概3天之内审核
private static final String TEMPLATEID=“9294239”;

//验证码长度,范围4~10,默认为4
private static final String CODELEN="6";

public static String senCode(String phone) throws Exception{
    
	HttpClient httpClient = new DefaultHttpClient();
    HttpPost httpPost = new HttpPost(SERVER_URL);
    String curTime = String.valueOf((new Date()).getTime() / 1000L);
    /*
     * 参考计算CheckSum的java代码,在上述文档的参数列表中,有CheckSum的计算文档示例
     */
    String checkSum = CheckSumBuilder.getCheckSum(APP_SECRET, NONCE, curTime);

    // 设置请求的header
    //开发者平台分配的appkey
    httpPost.addHeader("AppKey", APP_KEY);
    //随机数(最大长度128个字符)
    httpPost.addHeader("Nonce", NONCE);
    //	当前UTC时间戳,从1970年1月1日0点0 分0 秒开始到现在的秒数(String)
    httpPost.addHeader("CurTime", curTime);
    //SHA1(AppSecret + Nonce + CurTime),三个参数拼接的字符串,进行SHA1哈希计算,转化成16进制字符(String,小写)
    httpPost.addHeader("CheckSum", checkSum);
    httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");

    // 设置请求的的参数,requestBody参数
    List nvps = new ArrayList();
    /*
     * 1.如果是模板短信,请注意参数mobile是有s的,详细参数配置请参考“发送模板短信文档”
     * 2.参数格式是jsonArray的格式,例如 "['13888888888','13666666666']"
     * 3.params是根据你模板里面有几个参数,那里面的参数也是jsonArray格式
     */
    nvps.add(new BasicNameValuePair("templateid", TEMPLATEID));
    nvps.add(new BasicNameValuePair("mobile", phone));
    nvps.add(new BasicNameValuePair("codeLen", CODELEN));

    httpPost.setEntity(new UrlEncodedFormEntity(nvps, "utf-8"));

    // 执行请求
    HttpResponse response = httpClient.execute(httpPost);
    
    /*
     * 1.打印执行结果,打印结果一般会200、315、403、404、413、414、500
     * 2.具体的code有问题的可以参考官网的Code状态表
     */
    
    String string = EntityUtils.toString(response.getEntity(), "utf-8");
    
    String code =  JSON.parseObject(string).getString("code");
    if(code.equals("200")){
    	// 成功
    	System.out.println("发送成功,验证码为:"+JSON.parseObject(string).getString("obj"));
    	return "SUCCESS";
    }else{
    	return "ERROR";
    }
}

}
4,网易校验验证码工具类
package com.baizhi.util.wyy;
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;

/**

  • 网易校验验证码工具类

  • @author Administrator
    */
    public class MobileMessageCheck {
    private static final String SERVER_URL = “https://api.netease.im/sms/verifycode.action”;//校验验证码的请求路径URL
    private static final String APP_KEY = “5bc098dac74e4036de56617552e02447”;//网易云信分配的账号
    private static final String APP_SECRET = “d42974b591d4”;//网易云信分配的密钥
    private static final String NONCE = “123456”;//随机数

    public static String checkMsg(String phone, String code) 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 = new ArrayList();
     nameValuePairs.add(new BasicNameValuePair("mobile", phone));
     nameValuePairs.add(new BasicNameValuePair("code", code));
    
     post.setEntity(new UrlEncodedFormEntity(nameValuePairs, "utf-8"));
    
     //执行请求
     HttpResponse response = httpclient.execute(post);
     
     String responseEntity = EntityUtils.toString(response.getEntity(), "utf-8");
     System.out.println(responseEntity);
     // msg   obj  
     //判断是否发送成功,发送成功返回true
     String codeMessage = JSON.parseObject(responseEntity).getString("code");
     if (codeMessage.equals("200")) {
        return "SUCCESS";
     }
     return "ERROR";
    

    }
    }
    5,写controller方法调用接口实现短信验证码

你可能感兴趣的:(个人)