Java使用【网易云信】短信接口,给手机用户发送并校验验证码

感谢原作者,基本上拿来就可以用,但里面还是有一些小坑(主要是jar包的加载),所以转载过来,调整到适合我的状态。


网易云信地址:http://dev.netease.im/


我在本项目中使用到的jar包:

fastjson-1.1.36.jar

我的maven无法下载fastjson-1.1.36.jar,附外部地址

https://www.oschina.net/news/43956/fastjson-1-1-36

httpcore-4.4.5.jar

httpcore-ab-4.4.5.jar

httpcore-nio-4.4.5.jar

httpclient-4.5.jar

commons-codec-1.9.jar

commons-logging-1.2.jar


以上是原作者的包,我主要就是下载了以下2个包和fastjson-1.1.36.jar。

Jar包下载

httpcore-4.4.3.jar

  • [org.apache.http.HttpResponse]
  • [org.apache.http.NameValuePair]
  • [org.apache.http.message.BasicNameValuePair]
  • [org.apache.http.util.EntityUtils]

httpclient-4.5.1.jar

  • [org.apache.http.client.entity.UrlEncodedFormEntity]
  • [org.apache.http.client.methods.HttpPost]
  • [org.apache.http.impl.client.DefaultHttpClient]


因为移动端的方便,现在网络上很多的网站与应用都有与实现用户手机绑定的功能。这样做的好处很多,例如账号登陆、修改密码、在线支付……等功能模块都可以与手机实时获取验证码短信结合,来确保用户的安全性操作。


对于验证码的操作我们一般分为两个部分:
1.给手机用户发送验证码。
2.通过手机用户的反馈,我们需要校验用户输入的验证码是否正确。

一、
发送验证码
首先我们创建:校验码生成类
package com.mobile;

import java.security.MessageDigest;

/**
 * 验证码生成工具类
 * @author Administrator
 *
 */
public class CheckSumBuilder {

    //计算并获取checkSum
    public static String getCheckSum(String appSecret,String nonce,String curTime){
        return encode("SHA",appSecret+nonce+curTime);
    }

    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 sb=new StringBuilder(len*2);
        for(int $i=0;$i            sb.append(HEX_DIGITS[(bytes[$i]>>4)&0x0f]);
            sb.append(HEX_DIGITS[bytes[$i]&0x0f]);
        }
        return sb.toString();
    }

    private static final char[] HEX_DIGITS={'0','1','2','3','4','5','6',
            '7','8','9','a','b','c','d','e','f'};

}


然后我们再封装: 短信发送工具类
package com.mobile;

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;

/**
 * 短信发送工具类
 * @author Administrator
 *
 */
public class MobileMessageSend {
    private static final String SERVER_URL="https://api.netease.im/sms/sendcode.action";//发送验证码的请求路径URL
    private static final String APP_KEY="e8c86e26c09d*************";//网易云信分配的账号
    private static final String APP_SECRET="0177b8*****";//
网易云信分配的密钥
    private static final String NONCE="123456";//随机数

    public static String 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);

        //设置请求的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));

        post.setEntity(new UrlEncodedFormEntity(nameValuePairs,"utf-8"));

        //执行请求
        HttpResponse response=httpclient.execute(post);
        String responseEntity= EntityUtils.toString(response.getEntity(),"utf-8");

        //判断是否发送成功,发送成功返回true
        String code= JSON.parseObject(responseEntity).getString("code");
        if (code.equals("200")){
            return "success";
        }
        return "error";
    }
}


最后我们在main方法中测试: 发送验证码的测试类
package com.mobile;

/**
 * 发送验证码
 * 网易云信地址:http://dev.netease.im/
 * @author Administrator
 *
 */
public class SendMsg {
    public static void main(String[] args) {
        String mobileNumber = "185********";//接收验证码的手机号码
        try {
            String str = MobileMessageSend.sendMsg(mobileNumber);
            if("success".equals(str)){
                System.out.println("发送成功!");
            }else{
                System.out.println("发送失败!");
            }
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }
    }
}


二、校验验证码
我们先封装: 验证码检验工具类
package com.web;

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

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 com.alibaba.fastjson.JSON;
import com.mobile.CheckSumBuilder;

/**
 * 校验验证码工具类
 * @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="e8c86e26c09da8**************";//账号
    private static final String APP_SECRET="0177b8******";//密钥
    private static final String NONCE="123456";//随机数

    public static String 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 =new ArrayList<>();
        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");

        //判断是否发送成功,发送成功返回true
        String code= JSON.parseObject(responseEntity).getString("code");
        if (code.equals("200")){
            return "success";
        }
        return "error";
    }
}


我们在main方法中测试: 校验验证码的测试类
package com.web;

/**
 * 校验验证码
 * @author Administrator
 *
 */
public class CheckMsg {
    public static void main(String[] args) {
        String mobileNumber = "185********";//手机号码
        String code = "1071";//验证码
        try {
            String str = MobileMessageCheck.checkMsg(mobileNumber,code);
            if("success".equals(str)){
                System.out.println("验证成功!");
            }else{
                System.out.println("验证失败!");
            }
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }
    }
}

你可能感兴趣的:(Java使用【网易云信】短信接口,给手机用户发送并校验验证码)